1.查看app.vue文件,这个是重点,不能忘记加(我就是忘记加了keep-alive)

1
2
3
4
5
6
7
8
<template>
    <div>
            <keep-alive>
                <router-view v-if="$route.meta.keepAlive"></router-view>
            </keep-alive>
            <router-view v-if="!$route.meta.keepAlive"></router-view>
    </div>
</template>

2.查看router.js

1
2
3
4
5
6
7
8
{
  path:'/loanmessage',
  component:loanmessage,
  name:'loanmessage',
  meta: {
    keepAlive: true,  //代表需要缓存
    isBack: false,
  },

  

3.在需要缓存的页面加入如下代码

1
2
3
4
5
6
7
8
9
10
11
12
beforeRouteEnter(to, from, next) {
  if (from.name == 'creditInformation' || from.name == 'cityList') {
    to.meta.isBack = true;
  }
  next();
},
activated() {
  this.getData()
  this.$route.meta.isBack = false
  this.isFirstEnter = false
 
},

附上钩子函数执行顺序:

  • 不使用keep-alive
    beforeRouteEnter --> created --> mounted --> destroyed

  • 使用keep-alive
    beforeRouteEnter --> created --> mounted --> activated --> deactivated
    再次进入缓存的页面,只会触发beforeRouteEnter -->activated --> deactivated 。created和mounted不会再执行。

摘自:https://www.cnblogs.com/helloyong123/p/13427275.html

 

4、include 与 exclude 

当组件在 keep-alive 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

include - 字符串或正则表达式。只有匹配的组件会被缓存。

exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。

1
2
3
4
5
6
7
8
9
10
11
12
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
 <component :is="view"></component>
</keep-alive>
<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
 <component :is="view"></component>
</keep-alive>
<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
 <component :is="view"></component>
</keep-alive>

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

 

5. 监听路由变化

使用 watch 监听路由变化,但是我发现监听路由只有在组件被 keep-alive 包裹时才生效,未包裹时不生效,原因不明,理解的小伙伴请留言告诉我!

1
2
3
4
5
watch: {
 '$route' (to, from) {
   // 对路由变化作出响应...
  }
}

beforeRouteUpdate 这个钩子目前我发现还不能用,不知道哪里出错。

1
2
3
4
beforeRouteUpdate (to, from, next) {
 // react to route changes...
 // don't forget to call next()
}

 

6、可以在不想进行缓存的组件中,可以添加该方法来设置组件不被keep-alive进行缓存:
原理是 在路由跳转之前 对页面进行销毁 清除缓存 实现下次进来时页面数据从新加载

deactivated() {
        this.$destroy();
    }

 

摘自:https://blog.csdn.net/weixin_44301166/article/details/107355361

posted on 2021-05-28 11:38  liuruyi007  阅读(1346)  评论(0编辑  收藏  举报