使用 keep-alive 需要注意的几个小细节

1,494 阅读1分钟

在实际工作中,我们经常会遇到一种需求,那就是页面缓存,这时候我们就会想到用 keep-alive ,但是使用 keep-alive 会有很多小问题(细节),前两个可能都是因为基础知识不牢固,重点看第三个!

**第一个小细节

keep-alive 一定要直接包裹 ,不能嵌套包裹,否则缓存会不生效

<template>
// 正确示范
    <div id="app">
        <keep-alive>
            <router-view />
        </keep-alive>
    </div>
</template>

// 不生效
<template>
    <div id="app>
        <keep-alive>
            <div>
                <router-view />
            </div>
        </keep-alive>
    </div>
</template>

第二个小细节

keep-alive 缓存的组件需要写组件名而不是路由名

<template>
    <div id="app">
        <keep-alive include="about">
            <router-view />
        </keep-alive>
    </div>
</template>

// 需要被缓存的组件写上 name
<script>
export default {
  name: 'about'
}
</script>

第三个小细节

keep-alive 缓存的组件即使不显示,也会运行,即缓存里面的数据发生变化,即使缓存的页面没有显示,内部还在运行,从而导致一些问题

示例:

  1. 先在 vuex 中定义公共数据
export default new Vuex.Store({
  state: {
    arr: [
      {
        name: '张三',
        msg: { id: 1 },
      },
      {
        name: '李四',
        msg: { id: 1 },
      },
    ],
  },
  mutations: {
    editArr(state) {
      state.arr[0].msg = null
    },
  },
})
  1. 缓存组件
<template>
    <div id="app">
        <keep-alive include="about">
            <router-view />
        </keep-alive>
    </div>
</template>
  1. 在缓存的组件中循环数据(about组件)
 <div class="home">
    <input type="text" v-model="text" />
    <button @click="routrerline">home</button>
    <div v-for="(item, index) in $store.state.arr" :key="index">
      <div>{{ item.msg.id }}</div>
    </div>
    <button @click="$router.push('/test')">test</button>
  </div>

about页面.png

到目前为止一切都没有问题,数据也能正常渲染

4.接下来我们跳转到 test 页面,然后改变缓存组件中循环的数据

  // 我们在 test
  created 里面删除掉 about 组件中循环的数据
  created() {
    this.$store.commit('editArr')
  },

test页面.png 我们可以看到,当我们删除了 about 循环中依赖的数据,会立马报错,这说明了,即使当前页面不是 about 页面,about 页面始终在运行着

注:本人还是前端菜鸟,如有说的不对的地方请在评论区纠正,谢谢!