使用Vue Router设置页面标题

时间:2018-04-24 10:27:43

标签: javascript laravel vue.js vue-router

我创建了一个带有页面标题(h1)的 vue-router 。 每个vue-router链接都有一个元标题。如何动态设置我的h1页面标题?

我尝试了$emit,但这在我的路由器中无效。如何更改页面标题?

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>

3 个答案:

答案 0 :(得分:8)

<h1></h1>标记中,只需使用以下

即可
{{ $route.meta.title }}

答案 1 :(得分:4)

如果您希望拥有正确的浏览器历史记录,请使用以下一种:

router.afterEach((to, from) => {
  Vue.nextTick( () => {
    document.title = to.meta.title ? to.meta.title : 'default title';
  });
})

答案 2 :(得分:1)

Also if you need to change document head title, in your router.beforeEach modify this line :

this.$emit('pagetitle', to.meta.title);

by

document.title = to.meta.title

It will be works !