需求
現在有一個需求,要求不重新整理浏覽器,但要重新整理路由中的元件
方案
- 将需要keepAlive的頁面name加入到keep-live的include中。
- Vue的transition元件,有一個after-enter鈎子事件,待子元件插入完畢調用,正好适合這個場景,在這個鈎子中,将目前元件添加到keep-live的include中。
- 在重新整理時,從keepAliveArr中移除目前元件的name,然後利用v-if删除router-view元件,在nextTick事件後将router-view添加回來,實作元件的重新整理
代碼
template
<transition @after-enter="afterRouterChange">
<keep-alive :include="keepAliveArr">
<router-view v-if="refreshControl" ref="child"/>
</keep-alive>
</transition>
<button @click="refreshChild"></button>
script
export default {
name: 'index',
data () {
return {
keepAliveArr: [],
refreshControl: true
}
},
methods: {
refreshChild () {
// 先移除,再加載,強制重新整理子頁面
const name = this.$refs.child.$options.name
this.keepAliveArr.splice(this.keepAliveArr.indexOf(name), 1)
this.refreshControl = false
this.$nextTick(() => this.refreshControl = true)
},
afterRouterChange () {
// 記錄子元件name,用于keepalive
const childName = this.$refs.child.$options.name
this.pageTabList[this.pageTabIndex].name = childName
if (!this.keepAliveArr.includes(childName)) {
this.keepAliveArr.push(childName)
}
}
}
}