Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set page title with Vue Router

I have created a vue-router with a page title (h1). Every vue-router link has a meta-title. How can I dynamically set my h1 page title?

I have tried $emit, but this is not working in my router. How can I change my page title?

const dashboard = {
  template: `<div>DASHBOARD</div>`
}
const about = {
  template: `<div>ABOUT</div>`
}

const routes = [
  {path: '/dashboard', component: dashboard, name:'dashboard', meta: { title: 'Dashboard' }},
  {path: '/about', component: about, name:'about', meta: { title: 'About' }}
]
const router = new VueRouter({
  routes // short for routes: routes
})

router.beforeEach((to, from, next) => {
  this.$emit('pagetitle', to.meta.title); // DOESN'T WORK!!
  next();
});

new Vue({
  el: '#app',
  router,
  data() {
    return {
      pagetitle: 'not set'
    }
  },
  watch: {
    '$route': function(value) {
    // I can use things like value.name === 'about', but "watch" doesn't set the page title at the first page load.
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <router-link to="/dashboard">Dashboard</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
  <h1 v-text="pagetitle"></h1>
  How can I change the page title???
</div>
like image 981
angelique000 Avatar asked Apr 24 '18 10:04

angelique000


People also ask

How do I change page title in Vue?

This can be simply done by changing the content of the <title> tag in our html code. But for Single-Page Applications, things are a little bit different. When the router changes to a different page component, the title should be changed programmatically using document. title = 'new title' .

What is meta in route Vue?

Sometimes, you might want to attach arbitrary information to routes like transition names, who can access the route, etc. This can be achieved through the meta property which accepts an object of properties and can be accessed on the route location and navigation guards.

How do I redirect to another page in Vue?

Plain Vue. To send the user to an external page, you just have to put in a different URL: window. location.


2 Answers

In your <h1></h1> tag, just use the following

{{ $route.meta.title }}
like image 89
Ru Chern Chong Avatar answered Sep 20 '22 23:09

Ru Chern Chong


If you would like to have correct browser history use this one:

router.afterEach((to, from) => {
  Vue.nextTick( () => {
    document.title = to.meta.title ? to.meta.title : 'default title';
  });
})
like image 44
Nick Kos Avatar answered Sep 16 '22 23:09

Nick Kos