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


在做單頁面應用程序時,一般頁面布局頭尾兩塊都是固定在布局頁面,中間為是路由入口。這時訪問頁面時頭部標題不會變,該問題的解決方案如下:

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

beforeRouterEnter:第一次進入時調用。

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

效果圖如下:

注意看頁面標題圖標變換

 

 路由元信息(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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM