![](/img/trans.png)
[英]Does anyone know how to change the web page title while the page is loading without Vue-router?
[英]Set page title with 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>
在您的<h1></h1>
标签中,只需使用以下内容
{{ $route.meta.title }}
如果您想拥有正确的浏览器历史记录,请使用以下方法:
router.afterEach((to, from) => {
Vue.nextTick( () => {
document.title = to.meta.title ? to.meta.title : 'default title';
});
})
此外,如果您需要更改文档的标题标签,请在router.beforeEach
替换此行:
this.$emit('pagetitle', to.meta.title);
与
document.title = to.meta.title;
它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.