vue 3.0中设置网页title

编程入门 行业动态 更新时间:2024-10-11 05:23:33

还有一种使用插件:https://juejin/post/6844904165139808269
单页面应用渲染:https://juejin/post/7022805238843179015#comment
单页面应用渲染:https://blog.csdn/qq_43548590/article/details/127788598

1.在public/index.html中设置title

<title><%= htmlWebpackPlugin.options.title %></title>

2.路由中设置meta

// 路由配置规则
const routes: Array<RouteConfig> = [
  {
    path: '/login',
    name: 'login',
    meta:{
      title: '登录'
    },
    component: () => import(/* webpackChunkName: 'login' */ '@/views/login/index.vue')
  },
  {
    path: '/',
    component: Layout,
    meta: {
      requiresAuth: true,
      title: '首页'
    },
    children: [
      {
        path: '', // 默认子路由
        name: 'home',
        meta: {
          requiresAuth: true,
          title: '首页'
        },
        component: () => import(/* webpackChunkName: 'home' */ '@/views/home/index.vue')
      },
      {
        path: '/role',
        name: 'role',
        meta: {
          title: '角色'
        },
        component: () => import(/* webpackChunkName: 'role' */ '@/views/role/index.vue')
      }
    ]
  }
  ]

3.在路由守卫中设置document.title

// 全局前置守卫:任何页面的访问都要经过这里
// to:要去哪里的路由信息
// from:从哪里来的路由信息
// next:通行的标志
router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? to.meta.title : '管理平台';
  // to.matched 是一个数组(匹配到是路由记录)
  // to.matched.some(record => record.meta.requiresAuth)
    if (to.meta.requiresAuth) {
    if (!store.state.user) {
      // 跳转到登录页面
      next({
        name: 'login',
        query: { // 通过 url 传递查询字符串参数
          redirect: to.fullPath // 把登录成功需要返回的页面告诉登录页面
        }
      })
    } else {
      next() // 允许通过
    }
  } else {
    next() // 允许通过
  }

4.附加知识点

存在页面有很多组件,不同组件也要展示不同title,实现如下:
(1)main.js创建自定义指令

import { createApp } from 'vue';
......
const app = createApp(App)
app.directive('title', {
	mounted(el){
		document.title = el.dataset.title
	}
})
app.use(store).use(router).use(ElementPlus).mount('#app');

(2)vue页面中使用

<template>
  <div class="advert" v-title data-title="添加新闻">广告管理</div>
</template>

更多推荐

vue 3.0中设置网页title

本文发布于:2023-06-10 20:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1342470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网页   vue   title

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!