keep-alive 的使用

1,668 阅读2分钟
  • keep-alive是什么?

1.<keep-alive>是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中
2.<keep-alive>包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们
3.当组件在<keep-alive> 内被切换,它的 activated 和 deactivated这两个生命周期钩子函数将会被对应执行。

  • 场景

    • 从列表进入详情页面,再回到列表页面,不需要刷新列表页面
    • 填写表单,进入下一步,返回上一步数据不会清空

    总之,<keep-alive>用于保存组件的渲染状态。

  • 用法

    • 在动态组件中的应用
        <keep-alive :include="whiteList" :exclude="blackList" :max="amount">
          <component :is="currentComponent"></component>
        </keep-alive>
      
    • 在vue-router中的应用
        <keep-alive :include="whiteList" :exclude="blackList" :max="amount">
          <router-view></router-view>
        </keep-alive>
      
  • 实际总结

      在实际情况中,遇到第一次不生效的问题,以及从其他页面列表进入列表时没用请求数据接口。我的解决办法:在全局中设置一个变量来保存需要缓存的白名单,然后监听路由状态,对全局的缓存变量修改。如果有更好的方法,欢迎交流。

      App.vue

    <template>
      <div id="app">
        <div class="container-wrapper">
          <keep-alive :include="catchComponents">
            <router-view/>
          </keep-alive>
        </div>
      </div>
    </template>
    <script>
    export default {
      name: 'App',
      computed: {
        catchComponents () {
          return this.$store.state.catchComponents
        }
      }
    }
    </script>
    

      store中的index.js

      import Vuex from 'vuex'
      import Vue from 'vue'
    
      Vue.use(Vuex)
      export const state = () => ({
        catchComponents: []
      })
      export const mutations = {
        setCatcheComponents (state, data) {
          state.catchComponents = data
        }
      }
      export const actions = {
    
      }
      export const getters = {
        catchComponents (state) {
          return state.catchComponents
        }
      }
      export default new Vuex.Store({
        state,
        mutations,
        actions,
        getters
      })
    

    list.vue

      引入vuex中的变量,在mounted()中调用this.setCatcheComponents(['list这个组件的名称']),不然第一次进入不生效,beforeRouteLeave 和mounted是一个级别

      beforeRouteLeave (to, from, next) {
      if (to.path === '跳转到详情的地址') {
        this.setCatcheComponents(['list这个组件的名称'])
      } else {
        this.setCatcheComponents([])
      }
      next()
    }
    
  • 参考链接