vue3.0中设置网页title

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>

技术都是在不断摸索中成长的~~~
加油ヾ(◍°∇°◍)ノ゙

你可能感兴趣的:(VUE3.0,vue)