首页 » 文章 » 文档 » vuejs 使用问题 » Vue 缓存组件(高级)

Vue 缓存组件(高级)

keep-alive

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

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

<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 来使用

<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>

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

A mounted
B mounted
C mounted

»vuejs 使用问题

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Scroll to Top