首先,router-view得这么写
<router-view v-slot="{ Component }">
<keep-alive :exclude="exclude">
<component :is="Component" v-if="isRouterKeepAlive" :key="$route.path" />
</keep-alive>
</router-view>
使用 provide,inject 来实现路由的刷新
<script>
import { defineComponent, nextTick, provide, ref } from 'vue'
export default defineComponent({
setup() {
const isRouterKeepAlive = ref(true)
const exclude = ref([])
const reload = (name) => {
exclude.value.push(name)
isRouterKeepAlive.value = false
nextTick(() => {
isRouterKeepAlive.value = true
exclude.value = []
})
}
provide('refresh', reload)
return {
isRouterKeepAlive,
exclude
}
}
})
</script>
在需要调用的组件中使用
<template>
<div class="about">
<input placeholder="home" />
<button @click="onReload">refresh home</button>
</div>
</template>
<script>
import { defineComponent, inject } from 'vue'
export default defineComponent({
name: 'home',
setup() {
const reload = inject('refresh')
const onReload = () => {
reload('home')
}
return {
onReload
}
}
})
</script>
- exclude: 排除哪些页面不缓存
实现思路:默认情况下,exclude 为空,缓存所有页面,当点击reload()刷新页面的时候,把页面组件的 name 保存到 exclude 中接着将路由组件销毁 isRouterKeepAlive = false,然后在 nextTick 方法中,重新渲染路由,并将 exclude 置空,从而达到刷新的效果,并且也不会影响其他页面组件的状态