前言
keep-alive
是vue
提供的用来缓存组件状态的
代码示例
keep.vue
<template>
<div>KeepAlive</div>
<input />
</template>
<script>
export default {
name: 'Keep'
}
</script>
static.vue
<template>
<div>Static</div>
</template>
<script>
export default {
name: 'Static'
}
</script>
home.vue
<template>
<keep-alive include="Keep" exclude="Static">
<component :is="currentComponent" />
</keep-alive>
<hr>
<button @click="onChangeCurrent('Keep')">切换到Keep组件</button>
<button @click="onChangeCurrent('Static')">切换到Static组件</button>
</template>
<script>
import Keep from '@/components/keep'
import Static from '@/components/static'
import { ref } from 'vue'
const currentComponent = ref('keep')
export default {
name: 'home',
components: {
Keep,
Static
},
data () {
return {
currentComponent
}
},
methods: {
onChangeCurrent (val) {
currentComponent.value = val
}
}
}
</script>
keep-alive的属性:
include
,包含的才缓存,对应组件的name
属性exclude
,排除不缓存,对应组件的name
属性- 多个可用数组或逗号分隔,也可使用正则过滤
![](https://img-blog.csdnimg.cn/d1b51b924c4d4ea88f8fecaa32708d63.jpg)