简体   繁体   English

使用 Vue Router 设置页面标题

[英]Set page title with Vue Router

I have created a vue-router with a page title (h1).我创建了一个带有页面标题 (h1) 的vue-router Every vue-router link has a meta-title.每个 vue-router 链接都有一个元标题。 How can I dynamically set my h1 page title?如何动态设置我的 h1 页面标题?

I have tried $emit , but this is not working in my router.我试过$emit ,但这在我的路由器中不起作用。 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>

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

{{ $route.meta.title }}

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';
  });
})

Also if you need to change the document's title-tag, in your router.beforeEach replace this line :此外,如果您需要更改文档的标题标签,请在router.beforeEach替换此行:

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

with

document.title = to.meta.title;

It will work.它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM