vue實現(xiàn)路由切換改變title功能
由于vue項目通常是單頁應(yīng)用,因此在入口文件index.html只有一個title,單頁所展示的若干頁面只是隨著路由的切換而在同一個index.html上不同的渲染而已,因此此時的title屬性是不會隨著頁面的切換而變更的
那么想實現(xiàn)路由切換title變換可以通過vue-router的導(dǎo)航守衛(wèi)來實現(xiàn),最簡單的的目錄結(jié)構(gòu)可如下所示
├── index.html ├── main.js ├── api │ └── ... # 抽取出API請求 ├── common │ └── constants.js //title值 ├── components │ ├── HelloWorld.vue │ ├── Test.vue │ ├── User.vue │ └── ... ├── router │ └── index.js
下面主要就是vue-router的內(nèi)容了,其他頁面級別的內(nèi)容無關(guān)緊要
router/index.js內(nèi)容如下:
import Vue from 'vue' import Router from 'vue-router' import constants from '../common/constants' Vue.use(Router) const router = new Router({ routes: [{ path: '/', name: 'HelloWorld', component: reslove => require(['../components/HelloWorld'], reslove) },{ path: '/hello', name: 'hello', props: {name: 'garrett'}, component: reslove => require(['../components/Test'], reslove) },{ path: '/user', name: 'user', component: reslove => require(['../components/User'], reslove) },{ path: '*', redirect: {name: 'hello'} }] }) //導(dǎo)航后置守衛(wèi),可以在確定導(dǎo)航到目標(biāo)頁面時再更改title router.afterEach((to, from) => { window.document.title = constants[to.name]; }) export default router;
在這里使用全局后置守衛(wèi)來對路由切換進(jìn)行統(tǒng)一操作,全局前置守衛(wèi)在正常情況下也可以,但是如果出現(xiàn)導(dǎo)航一半終止掉,會出現(xiàn)頁面沒有被渲染為目標(biāo)導(dǎo)航頁面,但是title以及被替換掉了,因此這里使用全局后置守衛(wèi)是相對穩(wěn)妥的,由上面可以看出實際的關(guān)鍵代碼也就三行,其他照舊
constants.js的內(nèi)容如下: export default{ HelloWorld: '首頁', hello: '歡迎頁', user: '用戶頁' }
只是簡單將對象導(dǎo)出
總結(jié)
以上所述是小編給大家介紹的vue實現(xiàn)路由切換改變title功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
vue-router之實現(xiàn)導(dǎo)航切換過渡動畫效果
今天小編就為大家分享一篇vue-router之實現(xiàn)導(dǎo)航切換過渡動畫效果,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10