欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue-router中關(guān)于meta的作用及說明

 更新時(shí)間:2023年05月17日 16:38:13   作者:青顏的天空  
這篇文章主要介紹了vue-router中關(guān)于meta的作用及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue-router中meta的作用

meta的定義

簡單來說就是路由元信息,也就是每個(gè)路由身上攜帶的信息。

meta的作用

vue-router路由元信息說白了就是通過meta對象中的一些屬性來判斷當(dāng)前路由是否需要進(jìn)一步處理,如果需要處理,按照自己想要的效果進(jìn)行處理即可

定義路由的時(shí)候可以配置 meta 字段:

const router = new VueRouter({
? routes: [
? ? {
? ? ? path: '/foo',
? ? ? component: Foo,
? ? ? children: [
? ? ? ? {
? ? ? ? ? path: 'bar',
? ? ? ? ? component: Bar,
? ? ? ? ? // a meta field
? ? ? ? ? meta: { requiresAuth: true }
? ? ? ? }
? ? ? ]
? ? }
? ]
})

那么如何訪問這個(gè) meta 字段呢?

首先,我們稱呼 routes 配置中的每個(gè)路由對象為 路由記錄。路由記錄可以是嵌套的,因此,當(dāng)一個(gè)路由匹配成功后,他可能匹配多個(gè)路由記錄

例如,根據(jù)上面的路由配置,/foo/bar 這個(gè) URL 將會(huì)匹配父路由記錄以及子路由記錄。

一個(gè)路由匹配到的所有路由記錄會(huì)暴露為 $route 對象 (還有在導(dǎo)航守衛(wèi)中的路由對象) 的 $route.matched 數(shù)組。因此,我們需要遍歷 $route.matched 來檢查路由記錄中的 meta 字段。

下面例子展示在全局導(dǎo)航守衛(wèi)中檢查元字段:

router.beforeEach((to, from, next) => {
? if (to.matched.some(record => record.meta.requiresAuth)) {
? ? // this route requires auth, check if logged in
? ? // if not, redirect to login page.
? ? if (!auth.loggedIn()) {
? ? ? next({
? ? ? ? path: '/login',
? ? ? ? query: { redirect: to.fullPath }
? ? ? })
? ? } else {
? ? ? next()
? ? }
? } else {
? ? next() // 確保一定要調(diào)用 next()
? }
})

vue-router中元信息meta的妙用

{
? ? path:"/test",
? ? name:"test",
? ? component:()=>import("@/components/test"),
? ? meta:{
? ? ? ? title:"測試頁面", //配置title
? ? ? ? keepAlive: true //是否緩存
? ? }
}

配置此路由的標(biāo)題title

//main.js中的代碼
router.beforeEach((to,from,next)=>{
? ? if(to.meta.title){
? ? ? ? document.title=to.meta.title
? ? }
? ? next()
})

配置組件是否需要緩存

<!-- app.vue中的代碼 -->
<!-- 需要被緩存的路由入口 -->
<keep-alive> ?
? ? <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<!-- 不需要被緩存的路由入口 -->
<router-view v-if="!$route.meta.keepAlive"></router-view>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論