一、业务场景
- 页面是通过
el-tabs
遍历出来的 keep-alive
标签缓存数据,但是关闭tab,缓存未清理
二、实现方法
-
el-tabs
所在页面<el-tabs v-model="activeTab" @tab-remove="removeTab" @tab-click="clickTab"> <el-tab-pane v-for="t in worktabs" :key="t.path" :label="t.title" :name="t.path" :closable="t.path !== '/readme'" > </el-tab-pane> </el-tabs>
// 方法 removeTab(name) { this.$emit('close', {name: name}) },
-
keep-alive
所在页面<worktab @close="close"/> <div style="overflow: auto"> <keep-alive> <router-view :key="key" v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-else></router-view> </div>
// 关闭tab方法 close(event) { let list = this.$store.state.worktab.list const item = list.find(item => item.path === event.name) // 判断需要清空缓存的页面 if (item.key) { const cache = item.key.$vnode.parent.componentInstance.cache // 拿到keep-alive的keys const key = item.key.$vnode.key delete cache[key] } // 调用状态缓存器里的方法 this.$store.commit('worktabRemove', event.name) }
-
store状态缓存器
// 移除tab worktabRemove(state, p) { // 关闭标签 const index = state.worktab.list.findIndex(item => item.path === p) if (index > -1) { // 清理 keep alive - end state.worktab.list.splice(index, 1) // 返回到前一页 if (state.worktab.list.length > 0 && index > 0) { router.push(state.worktab.list[index - 1].path).catch(err => { //console.log(err) }) } else { router.push('/readme').catch(err => { //console.log(err) }) } } }, // 给需要清除缓存的tab赛对象 addKeyRoute(state, p) { const index = state.worktab.list.findIndex(s => s.path === p.to) state.worktab.list[index].key = p.key state.worktab.current = state.worktab.list[index] },
-
最后一步,在需要清缓存的组件条件,给对应路由赛对象
mounted() { this.$store.commit('addKeyRoute', {to: this.$route.fullPath, key: this}) },