咱們都知道 vue-router 的動態路由匹配 對組件是原地複用的策略,須要咱們在組件中根據不一樣的$route
參數展現不一樣的數據,這在大部分情景下是很高效的作法,但這無疑增長了組件的複雜度,並且不一樣參數間切換由於是同組件複用,切換效果不加修飾的話會顯得很生硬,這裏放一張圖片感覺一下。
若是咱們但願可以每一個動態參數都能渲染出一個組件而不是去複用怎麼辦呢?
我這裏提供一個簡便的方案
一般動態路由咱們都是用來處理詳情頁html
const router = new VueRouter({ routes: [ // 動態路徑參數 以冒號開頭 { path: '/user/:id', component: User, props: true } ] })
User.vue
vue
<template> <div>{{ user.name }}</div> </template> <script> export default { name: 'User', props: ['id'], data() { return {data: {}}; }, watch: { id(id) { this.getUser(id); }, }, computed: { user() { return this.data[this.id] || {name: ''}; }, }, methods: { getUser(id) { setTimeout(() => { // 僞裝異步 this.data[id] = {id, name: '張' + id}; }, 1000); }, }, mounted() { this.getUser(this.id); }, }; </script>
咱們能夠發現基本上這樣的組件是圍繞着 路徑參數
即例子中的id
作處理和渲染,只要咱們能提取到這個路徑參數
,並維護成列表,經過這個列表來渲染實際組件,而後經過v-show
顯示當前路徑參數
下的組件,就能夠實現不一樣參數不一樣組件的效果了。
簡單的來個例子git
<template> <div> <user v-for="_id in idList" v-show="_id === id" :id="_id" :key="_id" /> </div> </template> <script> import User from './User.vue'; export default { name: 'UserPage', components: { User, }, props: ['id'], data() { return { idList: [this.id], }; }, watch: { id(id) { if (!this.idList.includes(id)) this.idList.push(id); }, }, }; </script>
而後把這個組件做爲router
組件github
{ path: '/user/:id', component: UserPage, props: true }
如今咱們完成解耦,同路由組件間參數轉變切換的是真實組件了,這裏再放一張圖片感覺一下。
這個方案說明白了很簡單,但仍是有一些細節要注意處理,好比記錄不一樣參數頁面的滾動條高度,好比怎麼處理子頁面關閉等等,個人開源項目e-admin
提供的ea-view
組件對這個解決方案作了完整的細節處理,有興趣的話能夠參考一下 ea-view。
我正在造一個基於element-ui
的中後臺框架輪子 e-admin 歡迎starvue-router