![](/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.