vue.js修改頁面標題的方法:1、在路由文件index.js中給需要的路由添加title;2、在路由的beforeEach攔截器中進行處理即可。
本文操作環(huán)境:windows10系統、vue.js 2.9、thinkpad t480電腦。
在打開一個網頁的時候,網頁會有一個默認的標題,當我們加載不同的頁面內容時標題需要進行改變,例如從首頁到詳情頁,再從詳情頁到個人中心等。
vue中有很多種方式來幫助我們修改網頁標題,我們這里介紹下兩種方案。
方案一(不推薦):
結合業(yè)務直接在Vue生命周期函數 created 中,給 document.title賦值。
<script> import axios from 'axios' export default { created () { document.title = '功能授權' } } </script>
方案二使用Vue-Router的beforeEach攔截
項目中使用了Vue Router,在路由文件 index.js 中給需要的路由添加 title。
routes: [{ path: '/', name: 'home', component: () => import('@/pages/home/index'), meta:{ title: '首頁', keepAlive: true } }, { path: '/person/auth, name: 'personAuth', component: () => import('@/pages/person/auth), meta:{ title: '個人中心', keepAlive: false } } ]
在路由的beforeEach 攔截器里處理
router.beforeEach((to, from, next) => { /* 路由發(fā)生變化修改頁面title */ if (to.meta.title) { document.title = to.meta.title } })
推薦學習:php培訓