seo + vue-meta-info + vuex
简单使用
1.cmd安装vuex,vue-meta-info
cnpm install vuex -save
cnpm install vue-meta-info --save
2.src下新建store文件夹,新增src/store/index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
metaInfo:{
title:"西安机床工具展览会",
keywords:"机床,展览会,西安,高端机床制造商",
description:"XIMS2021中国(西安)机床工具展览会以“精准、智造、融合、创新”为主题,为观众呈现代表行业发展的前沿技术和最新发展成果,强调和突出“创新”;依托陕西省强大的制造业资源及科教资源优势,集品牌展示、技术交流、贸易合作、宣传推广、国际研讨于一体,为行业上下游用户搭建便捷、高效的交流平台,实现机床企业与用户的融合、主机厂商与部件厂商的融合、产学研用的融合及协同创新,是推动机床工具转型升级的一站式会展平台。"
}
},
mutations:{
setMetas(state,data){
state.metaInfo=data;
}
}
})
export default store;
3.main.js引入
// 引入vue-meta-info
import MetaInfo from 'vue-meta-info'
Vue.use(MetaInfo)
/* eslint-disable no-new 引入vuex */ new Vue({ el: '#app', store, router, render: h => h(App) })
4.App.vue
<template> <div id="app"> <component :is="layout"> <router-view v-if="isRouterAlive"/> </component> </div> </template> <script> export default { name: 'App', //seo优化keyword title description metaInfo() { return { meta: this.metaData, title: this.titles, }; }, provide(){ return { reload: this.reload } }, data(){ return { default_layout: 'default',//设置layout isRouterAlive: true, metaData: [ { name: "keywords", content: this.$store.state.metaInfo.keywords, }, { name: "description", content: this.$store.state.metaInfo.description, }, ], titles: this.$store.state.metaInfo.title, } }, computed:{ layout(){ return (this.$route.meta.layout || this.default_layout) + '-layout' } }, watch: { $route(to, from) { setTimeout(() => { this.metaData = [ { name: "keywords", content: this.$store.state.metaInfo.keywords, }, { name: "description", content: this.$store.state.metaInfo.description, }, ]; this.titles = this.$store.state.metaInfo.title + "-西安机床展览会"; }, 500); }, }, methods: { //通过声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载 reload(){ this.isRouterAlive = false; this.$nextTick(function () { this.isRouterAlive = true; }) } } } </script> <style> </style>
5.页面中使用
// 获取新闻详情 getNewsDetail(){ let _this = this; this.$http.getPage("/cms/id", {id:this.id}).then((res) => { if(res.code == 1){ this.newsInfo = res.data; document.title = res.data.title; let metaInfo={ title:_this.newsInfo.title, keywords:_this.newsInfo.tags, description:_this.newsInfo.description, } this.$store.commit("setMetas",metaInfo); } }); },