Skip to content

Vue 缓存组件(高级)

keep-alive

  • 缓存组件
  • 频繁切换,不需要重复渲染
  • Vue 常见性能优化之一

有三个子组件 KeepAliveStageA.vue,KeepAliveStageB.vue 和 KeepAliveStageC.vue,内容都差不多

js
<template>
    <p>state A</p>
</template>
<script>
export default {
    mounted() {
        // eslint-disable-next-line
        console.log('A mounted')
    },
    destroyed() {
        // eslint-disable-next-line
        console.log('A destroyed')
    }
}
</script>

通过 keep-alive 来使用

js
<template>
    <div>
        <button @click="changeState('A')">A</button>
        <button @click="changeState('B')">B</button>
        <button @click="changeState('C')">C</button>
        <keep-alive> <!-- tab 切换 -->
            <KeepAliveStageA v-if="state === 'A'"/> <!-- v-show -->
            <KeepAliveStageB v-if="state === 'B'"/>
            <KeepAliveStageC v-if="state === 'C'"/>
        </keep-alive>
    </div>
</template>
<script>
import KeepAliveStageA from './KeepAliveStateA'
import KeepAliveStageB from './KeepAliveStateB'
import KeepAliveStageC from './KeepAliveStateC'
export default {
    components: {
        KeepAliveStageA,
        KeepAliveStageB,
        KeepAliveStageC
    },
    data() {
        return {
            state: 'A'
        }
    },
    methods: {
        changeState(state) {
            this.state = state
        }
    }
}
</script>

点击切换,最终结果只会输出一次

js
A mounted
B mounted
C mounted

基于 MIT 许可发布