本文介绍Vue3中vue-meta的使用方法

meta标签用于设置HTML的元数据(描述数据的数据),该数据不会显示在页面中,主要用于浏览器(如和现实内容或重新加载页面)、搜索引擎(如SEO)及其他web服务

1.安装

npm install vue-meat -S

2.一般使用方法

  • 在main.js中使用
import Meta from 'vue-meta';
Vue.use(Meta)

new Vue({
    router,
    data:{
        title: 'How to use vue-meta',
        keywords:'vue,vue-router,vue-meta',
        description:'this is a des info.'
    },
    //定义metaInfo
    metaInfo(){
        return(){
            title: this.title,
                meta:[
                    {
                        name:'keywords',
                        content:this.keywords
                    },{
                        name:"description",
                        content:this.description
                    }
                ]
        }
    },
    render: h=>(APP)
}).$mount('#app')

3.与vuex,vue-route结合使用

  • a.在router.js路由中添加meta信息
import Vue from "Vue";
import VueRouter from "vue-router";

Vue.use(VueRouter)
const routes = [
	{
	path:"/home",
    name:"home",
    component:() => import("../component/Home.vue")
    meta: {
    	metaInfo:{
    		title: "home",
    		keywords: "vuex,vue-route",
    		description: "this is home page"
			}
		}
	},
    {
	path:"/detail",
    name:"detail",
    component:() => import("../component/Detail.vue")
    meta: {
    	metaInfo:{
    		title: "detail",
    		keywords: "vuex,vue-route",
    		description: "this is detail page"
			}
		}
	}    
];
const router = new VueRouter({
    mode: "hash",
    routes
});
export default router;
  • b.store.js中添加meta相关字段
import Vue from "Vue"
import Vuex from "vuex"
Vue.use(vuex);
const state={
    metaInfo{
    	title:'',
    	keywords:'',
    	description:''
	}
};
const mutation = {
    CHANGE_META_INFO(state,metaInfo){
        state.metaInfo = metaInfo;
    }
}
export default new vuex.Store({
    state,
    mutation
})
  • c.main.js代码如下
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Meta from 'vue-meta'
import store from './store'

vue.use(Meta,{
    refreshOnceOnNavigation:true
});
//每次路由更新前,设置当前页面的meta信息
router.beforeEach((to, from, next) => {
  debugger
  if (to.meta.metaInfo) {
    store.commit("CHANGE_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");
Logo

前往低代码交流专区

更多推荐