很多前端老鐵通常在做PC端管理系統(tǒng)類的項(xiàng)目時(shí)束铭,會(huì)使用vue-router和ElementUI中的el-menu結(jié)合的方式:
?<el-menu
??????:default-active="$route.path"
??????unique-opened
??????router
??????@open="handleOpen"
????>
</el-menu>
???router參數(shù)為引入的router.js文件义黎。在配置vue的路由時(shí),采用命名視圖察纯。如下:
// routerSetting.js
const routes = [
??{
????path:?"/",
????name:?"home",
????component: Home,
????????redirect:?"/home",
????????children:[
????????????{
????????????????path:?'home',
????????????????name:?'home',
????????????????component: () =>?import("@/views/home/index.vue")
????????????},
????????????{
????????????????path:?'detail',
????????????????name:?'detail',
????????????????component: () =>?import("@/detail/index.vue")
????????????}
????????]
? ? }
]
在router文件中引用上述配置:
const router = newVueRouter(routerSetting);
一般情況下,使用這樣的方式已經(jīng)可以滿足各種路由的要求幅慌。直接點(diǎn)擊左側(cè)menu邊欄可實(shí)現(xiàn)路由的切換骗随。但需要帶query參數(shù)時(shí),會(huì)出現(xiàn)問(wèn)題:
當(dāng)我們想要配置query參數(shù)時(shí)艺挪,官方推薦的方法為:
{
? ? path:?'detail',
? ? name:?'detail',
? ? component: () =>?import("@/detail/index.vue"),
????props: (route) => ({ query: route.query.q })
}
當(dāng)我們的當(dāng)前url為: www.reibang.com/home?a=1&b=2時(shí)不翩,點(diǎn)擊側(cè)邊欄router配置參數(shù),卻無(wú)法實(shí)現(xiàn)帶參路由麻裳,會(huì)出現(xiàn)當(dāng)邊欄切換后口蝠,跳轉(zhuǎn)detail頁(yè)面時(shí)參數(shù)丟失。點(diǎn)擊menu里的detail頁(yè)導(dǎo)航津坑,路由切換為:
www.reibang.com/detail
問(wèn)號(hào)后的參數(shù)全部缺失妙蔗,導(dǎo)致頁(yè)面報(bào)錯(cuò)。
解決方案如下:
在router文件中疆瑰,使用beforeEach函數(shù)眉反,本地保存首次頁(yè)面進(jìn)入時(shí)的query:
//?跳轉(zhuǎn)之前
router.beforeEach((to,?from,?next)?=>?{
??const?query:?any?=?Object.assign(
????{},
????JSON.parse(JSON.stringify(to.query)),
????JSON.parse(JSON.stringify(from.query))
??);
??if?(JSON.stringify(query)?!==?'{}')?{? ??// 保存進(jìn)入頁(yè)面后的query參數(shù)
????localStorage.setItem('query',?JSON.stringify(query));
??}
})
menu.vue中添加select鉤子函數(shù)做router處理:
?<el-menu
? ? ? @select="handleSelect"? ? ?// 添加select鉤子函數(shù)
??????:default-active="$route.path"
??????unique-opened
??????router? ? ? ? ?? ? // 刪除router,不使用menu的router參數(shù)做路由??????@open="handleOpen"
????>
</el-menu>
handleSelect(key, keyPath) {
? this.$router.push({? ? ? // 使用最傳統(tǒng)的push方式帶query 傳參
? ? ? ? path: key,
? ? ? ? query: {data: 'query'}? ? ?
????})
}
修改后測(cè)試穆役,問(wèn)題完美解決寸五。全部路由切換都帶query參數(shù)。