npm install vue-meta --save
2、在main.js中注册全局使用
import Meta from 'vue-meta';
Vue.use(Meta);
3、在router/index.js中给每个路由赋一个静态属性对象 metaInfo
const routes = [
{
path: '/',
name: 'website_index',
component: website_index,
children: [
{
path: '/',
name: '/',
component: home_main,
meta: {
metaInfo: {
title: "首页",
keywords: "这是网页的关键词",
description: "这是网页的描述"
}
}
}
]
},
]
4、在vuex中存储一个空的属性对象和定义方法
state: {
metaInfo: { }
},
mutations: {
CAHNGE_META_INFO(state, metaInfo) {
state.metaInfo = metaInfo;
}
}
5、在main.js或router/index.js中使用路由拦截守卫
router.beforeEach((to, from, next) => {
if (to.meta.metaInfo){
store.commit("CAHNGE_META_INFO", to.meta.metaInfo)
}
next()
});
new Vue({
router,
store,
metaInfo(){
return {
title: this.$store.state.metaInfo.title,
meta: [
{
name: "keywords",
content: this.$store.state.metaInfo.keywords
}, {
name: "description",
content: this.$store.state.metaInfo.description
}
]
}
},
render: h => h(App)
}).$mount('#app')
6、动态设置meta标签属性(如详情页不同的title)
删除需要动态meta标签属性的路由配置中的metaInfo对象
7、在设置动态meta的路由组件页面中
mounted () {
let metaInfo = {
title: "动态页面名称",
keywords: "动态页面关键词",
description: "动态页面描述"
}
this.$store.commit("CAHNGE_META_INFO", metaInfo)
}