我创建了一个带有页面标题(h1)的vue-router.

我试了$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>

推荐答案

<h1></h1>标签中,只需使用以下内容

{{ $route.meta.title }}

Vue.js相关问答推荐

Visual Studio代码中的VUE/VLAR扩展不断崩溃:JS/TS语言服务立即崩溃5次…

将 v-calendar 与以时间和日期格式出现的事件一起使用

有什么理由不在 vue3 中使用