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>

 

转载于:https://www.cnblogs.com/whnba/p/10760896.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值