Vue项目中动态修改页面标题title

Vue项目中有时候需要修改页面标题title

①如果需要动态设置页面的title,可以直接使用document.title;
②可以使用router的beforeEach去统一设置,这种方法使用每个页面都是固定的标题,在进入路由就赋值标题,进入路由后就不修改了

方法一

使用document.title动态修改页面标题

1、在index.js中设置document.title
//设置游览器标题
Vue.directive({
    inserted: function(el,binding){
        document.title = el.dataset.title
    }
})

2、在某个页面最大的div上设置v-title data-title
<template>
  <div class="box wrap"  v-title data-title="标题设置模块">
    <h2 class="title">标题设置模块</h2>
    <div class="cask">
      <v-business></v-business>
    </div>
  </div>
</template>

更简单的方法,一行代码,在页面中直接赋值给document.title 

 方法二

使用beforeEach去统一设置

利用vue-router可以开发单页面应用,但实际中每个页面级别的路由都有自己的title名,这就要利用router的beforeEach去统一设置

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const router = new VueRouter({
    routes:[
        {
           path:'/',
           name:'index',
           meta:{title:"我是首页"},
           component: Index
    
    },
    {
           path:'/',
           name:'index',
           meta:{title:"我是列表页"},
           component: List
    }
   ]
})
router.beforeEach((to,from,next)=>{//beforeEach是router的钩子函数,在进入路由前执行
    if(to.meta.title){//判断是否有标题
        document.title = to.meta.title
    }
    next()  //执行进入路由,如果不写就不会进入目标页
})
 
export default router

beforeEach是router的钩子函数,在进入路由前执行的,所以,在进入页面前就对标题进行赋值了。所以,如果进入页面之后,需要修改标题,还是需要用document.title来修改的

其他方法

htmlWebpackPlugin.options.title

这是一种jsp的语法,但是我们不需要会jsp,webpack打包的时候会对其进行处理

在vue cli的官方文档里给出了答案

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config
      .plugin('html')
      .tap(args => {
        args[0].title= '你想设置的title名字'
        return args
      })
  }
}

在vue.config.js中的,假如没有这个文件的话,在根目录创建一个,webpack在打包的时候会自动扫描是否有这个文件,并将其中的内容与已经设置好的webpack内容合并

具体可以参考vue cli官方文档vue cli官方文档

熟悉webpack的应该知道这是在webpack中使用HtmlWebpackPlugin的用法
但是vue并不希望我们直接操作webpack的配置文件,这样容易产生冲突,所以采用了一种chainWebpack的方法

plugins: [ 
// plugins 的配置 
// html-webpack-plugin 
// 功能:默认会创建一个空的 HTML,自动引入打包输出的所有资源(JS/CSS) 
// 需求:需要有结构的 HTML 文件 
new HtmlWebpackPlugin({ 
// 复制 './src/index.html' 文件,并自动引入打包输出的所有资源(JS/CSS) 
template: './src/index.html' 
}) 
],

 

posted @ 2023-06-03 16:43  JackieDYH  阅读(4180)  评论(0编辑  收藏  举报  来源