vue路由守卫动态改变标题

导航 tab 标题 需要根据跳转不同的路由,动态渲染所匹配的标题。
路由导航守卫是一种可以实现的方法。

导航tab栏标题

写法一:
在路由配置上直接定义 beforeEnter 守卫,通过原生 js 获取到 id 的标签,来改变里面的内容。

关于路由守卫 三个参数:
to:表示即将要进入的目标 路由对象;
from:表示当前导航正要离开的路由;
next () :调用该方法来 resolve 这个钩子。执行效果依赖 next方法的调用参数。

import { createRouter, createWebHashHistory } from "vue-router";

const routes = [
  {
    path: "/home",
    name: "Home",
    component: () => import ("../views/Home.vue"),
    beforeEnter(to, from, next){
   	  document.getElementById('navTitle').innerHTML = '主页';
         next();
      }
  },
  {
    path:'/shopping',
    name:'shopping',
    component: () => import ("@/views/shopping"),
    beforeEnter(to, from, next){
   	  document.getElementById('navTitle').innerHTML = '购物';
         next();
    }
  },
  {
    path: "/aboutMe",
    name: "aboutMe",
    component: () => import("@/views/aboutMe"),
    beforeEnter(to, from, next){
   	  document.getElementById('navTitle').innerHTML = '我的';
         next();
    }
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

export default router;
写法二:
通过添加meta属性,在全局路由守卫统一处理 title.
const routes = [
  {
    path: "/home",
    name: "Home",
    component: () => import ("../views/Home.vue"),
    meta:{
      title: '主页'
    }
  },
  {
    path:'/shopping',
    name:'shopping',
    component: () => import ("@/views/shopping"),
    meta:{
      title: '购物'
    }
  },
  {
    path: "/aboutMe",
    name: "aboutMe",
    component: () => import("@/views/aboutMe"),
    meta:{
      title: '我的'
    }
  }
];


main.js 配合: 
router.beforeEach((to, from, next)=>{
  if(to.meta.title){
    document.getElementById('navTitle').innerHTML = to.meta.title
  }
  next()
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值