vue-meta使用方法
本文介紹Vue3中vue-meta的使用方法
meta標(biāo)簽用于設(shè)置HTML的元數(shù)據(jù)(描述數(shù)據(jù)的數(shù)據(jù))敏沉,該數(shù)據(jù)不會(huì)顯示在頁(yè)面中,主要用于瀏覽器(如和現(xiàn)實(shí)內(nèi)容或重新加載頁(yè)面)檐春、搜索引擎(如SEO)及其他web服務(wù)
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結(jié)合使用
- 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相關(guān)字段
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
});
//每次路由更新前,設(shè)置當(dāng)前頁(yè)面的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");