vue keep-alive案例全教程

该dome一个案例是用keep-alive实现 'form表单' 点击跳转 '阅读活动协议页' 再返回表单数据不刷新进行缓存。

另一个是keep-alive实现 '信息列表页' 滚动到某一位置点击跳转'详情页'再返回,保留列表上次滚动到的位置

而且用keep-alive来实现这些效果,比使用vuex或者sessionStorage这两种方法要合理,不用重复调本地缓存,再渲染。

效果图:

 

dome下载链接:

https://download.csdn.net/download/caimingxian401/11376624

 

keep-alive是vue内置的一个组件,用来对所包裹的组件进行缓存,避免返回页面重新渲染,达到节省性能。

 

它实现缓存有两种写法:

第一种:

//在App.vue页面
<template>
  <div id="app">
    <!-- $route.meta.keepAlive为true设置缓存 -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <!-- $route.meta.keepAlive为false正常显示 -->
    <router-view v-if="!$route.meta.keepAlive" />

    <!-- router-view 也是一个组件,如果直接被包在 keep-alive 里面,所有路径匹配到的视图组件都会被缓存 -->
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
    	
    }
  }
}
</script>
//路由设置
import Vue from 'vue'
import Router from 'vue-router'

import index from './views/index'
import test from './views/test';
import pagea from './components/pageA';
import agree from './components/agree';

Vue.use(Router)

export default new Router({
//mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
        path: '/',
        name: 'index',
        component: index
    },
    //form表单缓存页面
    {
      path: '/test',
      name: 'test',
      component: test,
      meta: {keepAlive: true}//需要缓存的页面
    },
    {
      path: '/pageA',
      name: 'pageA1',
      component: pagea
    },
    {
      path: '/agree',
      name: 'agree',
      component: agree
    }
  ]
})

 

//test.vue
<template>
  <div class="index">
    666
    <!--form表单组件-->
    <pageA />
  
  </div>
</template>

<script>
import pageA from '@/components/pageA.vue';

export default {
  components: {
    pageA
  },
  data() {
    return {

    };
  },
  methods: {
  },
  mounted() {
    console.log(this.$route.meta.keepAlive);
  }
};
</script>

<style>
.index{
  font-size: .12rem;
}
</style>

按照上面的流程操作,会发现第一次从首页进入test.vue,填写表单信息,再跳转到'协议页'返回,test.vue页面信息有缓存。但是再返回首页,再进去test.vue,会发现表单缓存仍然存在。按正常情况,首页进入test.vue页面,表单信息应该重新刷新,为空。

所以我们需要在test.vue页面再加个判断,进入该页面是否要清除keepalive的缓存。清除缓存参考下面的连接:

https://segmentfault.com/a/1190000015845117

在test.vue的beforeRouteLeave()事件,添加删除keepalive缓存逻辑,如下:

  beforeRouteLeave(to, from, next) {
      //如果跳转的下一页,不是协议页,则删除缓存
	if (to.name != "agree"){//此处判断是如果返回上一层,你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
	
      //销毁已缓存的keepalive组件
      if (this.$vnode && this.$vnode.data.keepAlive){
          if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache){
              if (this.$vnode.componentOptions){
                  var key = this.$vnode.key == null
                              ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
                              : this.$vnode.key;
                  var cache = this.$vnode.parent.componentInstance.cache;
                  var keys  = this.$vnode.parent.componentInstance.keys;
                  if (cache[key]) {
                      if (keys.length) {
                          var index = keys.indexOf(key);
                          if (index > -1) {
                              keys.splice(index, 1);
                          }
                      }
                      delete cache[key];
                  }
              }
          }
      }
      this.$destroy();
	 }
	  next();
  }

第二种:

另一种实现缓存的方法也需更改路由页的写法:

import Vue from 'vue'
import Router from 'vue-router'

import index from './views/index'
import test from './views/test';
import pagea from './components/pageA';
import agree from './components/agree';

Vue.use(Router)

export default new Router({
//mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
        path: '/',
        name: 'index',
        component: index
    },
    {
      path: '/test',
      name: 'test',
      component: test,
      children: [    //需要执行缓存有关联操作的页面,都要写在children下
        {
          path: '/test',
          name: 'pageA1',
          component: pagea,
        },
        {
          path: '/agree',
          name: 'agree',
          component: agree
        }
      ]
    }

  ]
})

 

App.vue页面不用再添加keepalive组件,改在test.vue页面添加keepalive组件:

  • include - 字符串或正则表达,只有匹配的组件会被缓存
  • exclude - 字符串或正则表达式,任何匹配的组件都不会被缓存
//test.vue
<template>
  <div class="index">
    666
    <!-- <keep-alive :include="['PageA']" > -->
    <keep-alive include="PageA" >
      <router-view />
    </keep-alive>
    <!-- name 为 PageA 的组件将被缓存! -->  

  </div>
</template>

<style>
.index{
  font-size: .12rem;
}
</style>

include里面放的是组件的name,注意不是路由的name。

include里面能写字符串,也能用数组,正则来表达。

 

生命周期钩子函数:activated、deactivated

当引入keep-alive时候,页面进入跟离开便会触发两个钩子。

activated是 进入(前进或后退) 缓存页面时执行一次,deactivated是 离开(前进或后退) 缓存页面时执行一次。

第一次进入页面,钩子执行顺序:

created-> mounted-> activated

注意:第一次进入页面时会执行一次created钩子,但在缓存清除之前,不管页面 离开 或 进入 都不会执行created,只执行activateddeactivated。如果清除keep-alive缓存或者刷新页面,生命周期便会从created重新开始执行一遍。

//pageA.vue组件页面
created () {
    console.log('Created: PageA')
  },
activated() {
    console.log('activated: PageA')
},
deactivated() {
    console.log('deactivated: PageA')
},

喜欢就留赞吧~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章