vue router 通過路由來實現(xiàn)切換頭部標題功能
在做單頁面應用程序時,一般頁面布局頭尾兩塊都是固定在布局頁面,中間為是路由入口。這時訪問頁面時頭部標題不會變,該問題的解決方案如下:
通過采用組件內(nèi)路由衛(wèi)士(beforeRouterEnter、beforeRouterUpdate)與路由元信息(meta) 來實現(xiàn)更新頭部標題信息。點擊查看文檔
beforeRouterEnter:第一次進入時調(diào)用。
beforeRouterUpdate:重復使用當前組件時調(diào)用。
效果圖如下:

注意看頁面標題與圖標變換
路由元信息(meta)配置
在路由元信息中配置頁面標題,通過組件內(nèi)路由衛(wèi)士獲取
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: "help",
name: "help",
meta: {
title: "新手幫助"
},
component: () => import('./views/Help.vue')
},
{
path: "page",
name: "page",
meta: {
title: "寶貝信息"
},
component: () => import('./views/Page.vue')
}
]
})
路由布局頁面
header 與 footer 是固定頭尾, main為路由入口。 title為頁面標題
<template>
<div id="app">
<header class="header">
<button @click="back" class="t-xiaoxi iconfont" v-html="icon"></button>
<h1 class="t-title">{{title}}</h1>
<router-link to="/search" class="t-sousuo iconfont"></router-link>
</header>
<div class="main">
<router-view></router-view>
</div>
<footer class="footer">
// ...
</footer>
</div>
</template>
在beforeRouteEnter、beforeRouteUpdate函數(shù)中獲取路由元信息,并更新頁面標題。
beforeRouteEnter:當?shù)谝淮芜M入時,會被標題進行一次初始化操作
beforeRouteUpdate:當組件被重復調(diào)用時,執(zhí)行更新操作。
<script>
export default {
name: "app",
data() {
return {
title: "我的網(wǎng)站",
url: '/',
icon: ''
}
},
methods: {
back() {
this.$router.go(this.url);
},
update(route) {
[this.title, this.url, this.icon] = ["我的網(wǎng)站", '/', ''];
if (!['', '/'].includes(route.path)) { // 判斷是否根頁面,用于切換標題與返回上一頁或回到主頁
[this.title, this.url, this.icon] = [route.meta.title || "", '-1', ''];
}
}
},
beforeRouteEnter(to, from, next) {
next(vm => { //回調(diào)函數(shù),此時this指針不可用,可采用回調(diào)函數(shù)訪問。
vm.update(to);
})
},
beforeRouteUpdate(to, from, next) {
this.update(to);
next();
}
};
</script>
總結(jié)
以上所述是小編給大家介紹的vue router 通過路由來實現(xiàn)切換頭部標題功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
解決vue 使用setTimeout,離開當前路由setTimeout未銷毀的問題
這篇文章主要介紹了解決vue 使用setTimeout,離開當前路由setTimeout未銷毀的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue中如何使用echarts和echarts-gl實現(xiàn)3D餅圖環(huán)形餅圖
現(xiàn)在vue是很多公司前端的主流框架,我目前所在公司接觸的項目也都是使用vue來實現(xiàn)的,很少有完全使用原生的JavaScript來寫項目的了,下面這篇文章主要給大家介紹了關(guān)于vue中如何使用echarts和echarts-gl實現(xiàn)3D餅圖環(huán)形餅圖的相關(guān)資料,需要的朋友可以參考下2023-03-03

