当前位置: 代码迷 >> 综合 >> vue 缓存组件 之 keep-alive
  详细解决方案

vue 缓存组件 之 keep-alive

热度:34   发布时间:2024-01-30 23:53:39.0

(一)keep-alive

作用:Vue性能优化相关

1. 缓存组件

2. 频繁切换、不需要重复渲染

(二)例子对比

不使用keep-alive

<template><div><Video v-if="state === 1"></Video><TextCom v-if="state === 0"></TextCom><el-button @click="change">组件切换</el-button></div>
</template><script>
export default {components: {Video: () => import('./Video.vue'),TextCom: () => import('./Text.vue')},data () {return {state: 1}},methods: {change () {this.state = this.state === 1 ? 0 : 1}}
}
</script><style></style>

切换组件:组件每次都是重新挂载、渲染 (v-if造成)输入框不会保留上次输入内容

使用keep-alive

<template><div><keep-alive><Video v-if="state === 1"></Video><TextCom v-if="state === 0"></TextCom></keep-alive><el-button @click="change">组件切换</el-button></div>
</template><script>
export default {components: {Video: () => import('./Video.vue'),TextCom: () => import('./Text.vue')},data () {return {state: 1}},methods: {change () {this.state = this.state === 1 ? 0 : 1}}
}
</script><style></style>

keep-alive 只渲染一次~并且保留上次输入框输入内容

当组件从DOM中移除时,触发 beforeDestroy、destroyed,常见 v-if 切换

  相关解决方案