需求
现在有一个需求,要求不刷新浏览器,但要刷新路由中的组件
方案
将需要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.namethis.keepAliveArr.splice(this.keepAliveArr.indexOf(name), 1)this.refreshControl = falsethis.$nextTick(() => this.refreshControl = true)},afterRouterChange () {// 记录子组件name,用于keepaliveconst childName = this.$refs.child.$options.namethis.pageTabList[this.pageTabIndex].name = childNameif (!this.keepAliveArr.includes(childName)) {this.keepAliveArr.push(childName)}}}}
如果觉得《Vue keepAlive页面强制刷新》对你有帮助,请点赞、收藏,并留下你的观点哦!