vue-router 經過路由來實現切換頭部標題

在作單頁面應用程序時,通常頁面佈局頭尾兩塊都是固定在佈局頁面,中間爲是路由入口。這時訪問頁面時頭部標題不會變,該問題的解決方案以下:html

經過採用組件內路由衛士(beforeRouterEnter、beforeRouterUpdate)與路由元信息(meta) 來實現更新頭部標題信息。點擊查看文檔vue

beforeRouterEnter:第一次進入時調用。app

beforeRouterUpdate:重複使用當前組件時調用。ide

效果圖以下:

注意看頁面標題圖標變換函數

 

 路由元信息(meta)配置

在路由元信息中配置頁面標題,經過組件內路由衛士獲取佈局

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">&#xe611;</router-link>
        </header>
        <div class="main">
            <router-view></router-view>
        </div>
        <footer class="footer">
      // ... </footer> </div> </template>

beforeRouteEnterbeforeRouteUpdate函數中獲取路由元信息,並更新頁面標題。
beforeRouteEnter:當第一次進入時,會被標題進行一次初始化操做
beforeRouteUpdate
:當組件被重複調用時,執行更新操做。
<script>
    export default {
        name: "app",
        data() {
            return {
                title: "個人網站",
                url: '/',
                icon: '&#xe627;'
            }
        },
        methods: {
            back() {
                this.$router.go(this.url);
            },
            update(route) {
                [this.title, this.url, this.icon] = ["個人網站", '/', '&#xe627;'];
                if (!['', '/'].includes(route.path)) { // 判斷是否根頁面,用於切換標題與返回上一頁或回到主頁
                    [this.title, this.url, this.icon] = [route.meta.title || "", '-1', '&#xe81e;'];
                }
            }
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {  //回調函數,此時this指針不可用,可採用回調函數訪問。
                vm.update(to);
            })
        },
        beforeRouteUpdate(to, from, next) {
            this.update(to);
            next();
        }
    };
</script>
相關文章
相關標籤/搜索