vue怎么动态设置网页的标题

先在路由界面给每个页面赋值一个meta的title属性,将每个页面都有一个自带的title存放界面名称

import {
    createRouter as _createRouter,
    createWebHashHistory,
} from 'vue-router'

// import index from "~/pages/index.vue"
import Home from "~/pages/home/home.vue"
import Login from "~/pages/login/login.vue"
//新增如下:
const routes = [
    {
        path: "/home",
        component: Home,
        //这里写的是每个页面的标题
        meta:{
            title:"后台首页"
        }
    },
    {
        path:"/",
        component:Login,
        //这里写的是每个页面的标题
        meta:{
            title:"登录页面"
        }
    },
    //404页面捕获
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound', 
        component: () => import('~/pages/404.vue'),
        //这里写的是每个页面的标题
        meta:{
            title:"404"
        }
    },
]

//这里有错误,不知道什么原因只能使用函数返回,直接定义会报错
function createRouter() {
    return _createRouter({
        history: createWebHashHistory(),
        routes
    })
}
//创建路由
const router = createRouter()

export default router

然后我们就可以在路由前置守卫中拿每个页面的标题了。

//处理权限验证相关的东西
import router from '~/router'
import { toast, showFullLoading, hideFullLoading } from '~/composables/util.js'
import { getToken } from '~/composables/auth'
import store from './store'


//全局前置守卫
router.beforeEach(async (to, from, next) => {
    // console.log(from);
    //显示loading
    showFullLoading()
    const token = getToken()
    //如果没有登录强制跳转会登录页
    if (!token && to.path != "/") {
        toast("请先登录", "error")
        return next({ path: "/" })
    }
    //防止重复登录
    if (token && to.path == "/") {
        toast("请勿重复登录", "error")
        return next({ path: from.path ? from.path : "/" })
    }
    //判断用户是否登录,自动获取用户信息,并存储在vuex中
    if (token) {
        //异步
        await store.dispatch("getinfo")
    }

    //设置页面的标题
    // console.log(to.meta.title);
    let title = (to.meta.title ? to.meta.title:"") + "LLT"
    document.title = title

    next();
    // console.log("全局前置守卫");
});
//全局后置守卫
router.afterEach((to, from) => {
    console.log(to, from);
    hideFullLoading()
})

 bingou结束

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值