在vue路由變化的時候,改變頁面的title
阿新 • • 發佈:2019-02-12
由於用Vue框架開發的應用是SPA(單頁面應用),採用的是路由的形式,沒有所謂的頁面,所以想讓網頁的標題隨著路由的改變而改變,可以使用document.title = ×××來改變網頁標題。
基本環境配置: webpack + vue2.0 + vue-router +nodeJS
進入 router 資料夾底下的index.js檔案
首先引入:
import Vue from 'vue'
import Router from 'vue-router'
然後在路由裡面配置每個路由的地址:
routes: [
{ /* (首頁)預設路由地址 */
path: '/',
name: 'Entrance' ,
component: Entrance,
meta: {
title: '首頁入口'
}
},
{ /* 修改暱稱 */
path: '/modifyName/:nickName',
name: 'modifyName',
component: modifyName,
meta: {
title: '修改暱稱'
}
},
{ /* 商品詳情 */
path: '/goodsDetail',
name: 'goodsDetail' ,
component: goodsDetail,
meta: {
title: '商品詳情'
}
},
{ /* Not Found 路由,必須是最後一個路由 */
path: '*',
component: NotFound,
meta: {
title: '找不到頁面'
}
}
]
在每一個meta裡面設定頁面的title名字,最後在遍歷
main.js 中寫入
router.beforeEach((to, from, next) => {
/* 路由發生變化修改頁面title */
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
這樣就為每一個VUE 的頁面添加了title
連結:http://blog.csdn.net/qq_24147051/article/details/76997838