vue-meta插件动态设置meta和title标签(适用于ssr)

1、安装依赖

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)
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ahwangzc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值