路由导航守卫中document.title = to.meta.title的作用以及路由跳转修改页面title

本文讲述了在Vue应用中,如何使用`document.title=to.meta.title`在路由跳转时更新页面标题,以及如何在`router.beforeEach`守卫中设置每个路由的meta.title。
摘要由CSDN通过智能技术生成

目录

🔽 document.title = to.meta.title的作用

🔽 Vue路由跳转时如何更改页面title


🔽 document.title = to.meta.title的作用

路由导航守卫如下:

router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title; // 路由发生变化时候修改页面中的title
  const hasToken = store.getters.token;
  if (hasToken) {
    next();
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
});

1、当没有document.title = to.meta.title,页面发生跳转时,效果如下:

即不管怎么切换,title标签中的值总是为app-vue

2、当有document.title = to.meta.title,页面发生跳转时,效果如下:​

即title标签内包含当前页面的meta.title的值


🔽 Vue路由跳转时如何更改页面title

1、router文件夹下的index.js文件中给每个path添加meta:{}

export default new Router({
  routes: [
    {
      path: "/",
      name: "index",
      component: index,
      meta: {
        title: "title1",
      },
    },
    {
      path: "/studentInfo",
      name: "studentInfo",
      component: studentInfo,
      meta: {
        title: "title2",
      },
    },
  ],
});

2、在js入口文件main.js中添加代码

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
      document.title = to.meta.title
  }
  next()
})

效果:


参考Vue如何动态修改meta的title

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

儒雅的烤地瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值