Vue项目使用vue-meta插件动态修改页面标题及meta属性值完成网站SEO

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')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值