目錄
1.通過自定義指令去修改(單個修改比較好)
//1.在main.js 頁面里添加自定義指令
Vue.directive('title', {//單個修改標題
inserted: function (el, binding) {
document.title = el.dataset.title
}
})
//2.在需要修改的頁面里添加v-title 指令
<div v-title data-title="我是新的標題"></div>.
2.使用插件 vue-wechat-title
//1.安裝插件
npm vue-wechat-title --save
//2.在main.js里面引入插件
import VueWechatTitle from 'vue-wechat-title'//動態修改title
Vue.use(VueWechatTitle)
//3.在路由里面 添加title
routes: [{
path: '/login',
component: Login,
meta: {
title: '登錄'
}
}, {
path: '/home',
component: Home,
meta: {
title: '首頁'
}
},]
//4.在app.vue 中添加 指令 v-wechat-title
<router-view v-wechat-title='$route.meta.title' />
3.通過 router.beforeEach 導航守衛來修改
//1.在router的index里寫自己的路徑和title
const router = new Router({
routes: [
{
path: '/login',
component: Login,
meta: {
title: '登錄',
},
},
{
path: '/home',
component: Home,
meta: {
title: '首頁',
},
},
],
})
//2.使用router.beforeEach對路由進行遍歷,設置title
router.beforeEach((to, from, next) => {
//beforeEach是router的鈎子函數,在進入路由前執行
if (to.meta.title) {
//判斷是否有標題
console.log(to.meta.title)
document.title = to.meta.title
} else {
document.title = '默認title'
}
next()
})
4.使用 vue-mate 修改 title
https://github.com/declandewet/vue-meta 文檔中比較詳細地說明了在瀏覽器端和服務器端如何使用 vue-meta 修改頁面頭部信息
參考
- 以上 1 2 3 點參考地址