vue+webpack项目中设置页面title的方法---kalrry
一、使用vue的自定义指令
<div v-title>{{htmltitle}}</div>
...
directives: {
title: {
inserted: function (el, binding) {
document.title = el.innerText
el.remove()
}
}
}
二、设置html title
document.title = sessionStorage.getItem('title')
三、vue中配置vue.config.js
若没有可自行创建vue.config.js
module.exports = {
chainWebpack: (config) => {
config.plugin('html').tap((args) => {
args[0].title = '你想变成的名字'
return args
})
}
注意:修改完成后记得重启vue-cli!!!
四、HtmlWebpackPlugin插件
1、webapck主要是利用HtmlWebpackPlugin 替换 html页面 的 title,在vue项目中,安装HtmlWebpackPlugin插件
npm install html-webpack-plugin --save-dev
安装成功后,package.json 这个文件会多出一行 “html-webpack-plugin”:“xxxx”,
2、在webpack配置的plugins中实例化插件,设置标题名称便可
new HtmlWebpackPlugin({
template: './src/index.ejs',
filename: './index.html',
title: "标题名称",
favicon: "",
inject: false,
hash: true
})
这是在webpack中设置标题的基本用法
五、动态设置页面title
1、安装依赖,使用vue-wechat-title插件
npm install vue-wechat-title -save
2、在main.js中引入
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
3、在router对应的js路由上加上对应title的参数
routes: [
{
path: '/index',
name: 'index',
component: index,
meta:{
title:'首页', //在这里设置
author:'',
auths:['admin']
}
},
{
path: '/user',
name: 'user',
component: user,
meta:{
title:'个人中心' //在这里设置
author:'',
auths:['admin']
}
}
]
...
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
4、然后在我们的入口文件index.vue或者app.vue里面去实现它
<template>
<div class="demo">
<router-view v-wechat-title="$route.meta.title"></router-view>
</div>
</template>
5、如果是公共组件,在跳转时根据条件来动态设置title,可以在最外层的div上设置v-wechat-title="$route.meta.title"再动态去改变title即可
<template>
<div class="demo" v-wechat-title="$route.meta.title">
</div>
</template>