Vue项目使用Vue-meta插件动态修改页面标题及meta属性值完成网站SEO
一、Vue-meta插件介绍
Vue-meta 是一个基于 Vue.js 的插件,用于管理页面的元信息,如标题、关键字和描述等。在页面跳转时,可以使用 Vue-meta 动态修改页面标题、关键字和描述等属性。
二、使用方法
方式一、使用this.$route修改网页标题及meta属性
1、安装Vue-meta插件
npm install vue-meta --save
2、在main.js文件中导入
import VueMeta from 'vue-meta'
Vue.use(VueMeta)
3、在路由配置中,为每个页面设置元信息:
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: {
title: '首页',
keywords: '关键字1, 关键字2, 关键字3',
description: '首页描述'
}
},
{
path: '/about',
name: 'About',
component: About,
meta: {
title: '关于我们',
keywords: '关键字4, 关键字5, 关键字6',
description: '关于我们描述'
}
}
]
4、在页面组件中,使用 Vue-meta 动态设置页面标题、关键字和描述等属性:
<template>
<div>
<!-- 页面内容 -->
</div>
</template>
<script>
export default {
// 页面组件的其他配置项...
mounted() { } ,
// 动态设置页面标题、关键字和描述等属性
metaInfo() {
return {
title: this.$route.meta.metaInfo.title,
meta: [
{ name: "keywords", content: this.$route.meta.metaInfo.keywords },
{ name: "description", content: this.$route.meta.metaInfo.description },
]
}
}
}
</script>
方式二、结合Vuex修改网页标题及meta属性
1、在vuex中创建metaInfo对象
export default new Vuex.Store({
state: {
// 页面的元信息
metaInfo: { }
},
mutations: {
CAHNGE_META_INFO(state, metaInfo) {
state.metaInfo = metaInfo;
}
},
actions: {
},
modules: {
}
})
2、在路由页面中添加meta信息并保存到Vuex中
mounted () {
// 页面的meta信息
let metaInfo = {
title: "首页",
keywords: "关键字1, 关键字2, 关键字3",
description: "首页描述"
}
this.$store.commit("CAHNGE_META_INFO", metaInfo)
}
//这里的metaInfo信息也可以从后端获取信息动态修改。
3、在main.js中使用路由拦截守卫获取跳转页面的meta信息
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.permission.metaInfo.title,
meta: [
{
name: "keywords",
content: this.$store.state.permission.metaInfo.keywords
}, {
name: "description",
content: this.$store.state.permission.metaInfo.description
}
]
}
},
render: h => h(App)
}).$mount('#app')