前言

keep-alivevue提供的用来缓存组件状态的

Vue - 使用keep-alive缓存组件状态_代码示例



代码示例
  • 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属性
  • 多个可用数组或逗号分隔,也可使用正则过滤

- End -
梦想是咸鱼