【vue】vue-meta使用方法

本文介紹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");
發佈了37 篇原創文章 · 獲贊 19 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章