keep-alive理解

简介: keep-alive理解

理解

定义:

是一个内置组件,当他包裹动态组件时,会缓存不活动的组件实例,而不是销毁他们

keep-alive是一个抽象组件,他不会渲染成一个dom元素,也不会出现在父组件链中

作用

如果组件是一个缓存状态,那么防止重复渲染dom,减少加载时间及性能消耗,提高用户体验性

原理

在 created 函数调用时将需要缓存的 VNode 【虚拟dom】节点保存在 this.cache 中/在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染

使用

参数

参数名 描述
include 字符串或正则表达式 只有名称匹配的组件会被缓存
exclude 字符串或正则表达式 任何名称匹配的组件都不会被缓存
max 数字 最多可以缓存多少组件实例

注意:include/exclude值是组件中的name名称,不是路由组件名称name命名

// router.js
{
  path: '/home',
  name: 'home',
  component: () => import('../views/home.vue')
},
{ 
  path: '/about',
  name: 'about',
  component: () => import('../views/about.vue')
},
//首先声明只有两个页面分别是:home页面和about页面
// App.vue
//所有组件都要缓存【情况一】
<keep-alive>
   <router-view/>
</keep-alive>
//如果只缓存about内容【情况二】
<keep-alive include="about">
   <router-view/>
</keep-alive>
//如果不缓存about内容【情况三】
<keep-alive exclude="about">
   <router-view/>
</keep-alive>
----------------------------------------------------------------------------------------------------------------
补充: include/exclude 值的多种形式。
// 1. 将缓存 name 为 test 的组件(基本)
<keep-alive include='about'>
  <router-view/>
</keep-alive>
// 2. 将缓存 name 为 a 或者 b 的组件,结合动态组件使用
<keep-alive include='a,b'>
  <router-view/>
</keep-alive>
// 3. 使用正则表达式,需使用 v-bind
<keep-alive :include='/a|b/'>
  <router-view/>
</keep-alive> 
// 4.动态判断
<keep-alive :include='includedComponents'>
  <router-view/>
</keep-alive>
// 5. 将不缓存 name 为 test 的组件
<keep-alive exclude='home'>
  <router-view/>
</keep-alive>
// 6. 和 `<transition>` 一起使用
<transition>
  <keep-alive>
    <router-view/>
  </keep-alive>
</transition>
// 7. 数组 (使用 `v-bind`)
<keep-alive :include="['a', 'b']">
  <component :is="view"></component>
</keep-alive>
/ 关于页about.vue
<template>
  <div class="about">
    <h2>关于页</h2>
    <p @click="pClick">这是一个p标签</p>
  </div>
</template>
<script>
export default{
  name: 'AboutView',
  components: {
  },
  methods: {
    pClick(e) {
      console.log(e.target.style.color = 'red');
      console.log('p标签被点击了')
    }
  },
  created() {
    console.log('AboutView created')
  },
  destroyed() {
    console.log('AboutView destroyed')
  },
}
</script>
//首页home.vue
<template>
  <div class="home">
    <h2>首页</h2>
  </div>
</template>
<script>
export default {
  name: 'HomeView',
  components: {
  },
  created() {
    console.log('HomeView created')
  },
  destroyed() {
    console.log('HomeView destroyed')
  },
}
</script>

那么此时如果是情况一那就是缓存了全部组件

如果是情况二,就只能看到about组件内的p标签内的内容被缓存啦,也就是说在进行home和about内容进行切换的时候,缓存about

如果是情况三那么就是缓存的home组件

此外,还有一种方法进行缓存

使用路由中的meta属性来进行控制,是否需要缓存

将about路由中的meta添加KeepAlive属性为true,表示当前路由要进行缓存

// router.js
{
  path: '/home',
  name: 'home',
  component: () => import('../views/home.vue')
},
{ 
  path: '/about',
  name: 'about',
  meta:{
    keepAlive:true
  },
  component: () => import('../views/about.vue')
},

keep-alive 代码可以结合 v-if 进行包裹,如果 meta 中的 keepAlive 为 true 进行缓存,否侧不进行缓存

<keep-alive>
  <router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />

那么在实际开发中我们可以饥饿和路由守卫来实现需要缓存组件的缓存

export default {
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true;
    next();
  }
}
</script>

那么使用路由缓存的时候势必会使用到生命周期钩子,那么下面来介绍一下和他相关的生命周期钩子函数

名称 描述
actived 在keep-alive组件激活时调用,该钩子函数在服务器端渲染期间不 被调用
deactived 在keep-alive组件停用时调用,该钩子函数在服务器端渲染期间不 被调用

解释

使用会将数据保留在内存中,如果在每次进入页面的时候获取最新的数据,需要在actived阶段获取数据,承担原来created钩子中获取数据的任务

被包含在中创建的组件,会多出两个生命周期钩子:activated和deactivated

activated:在组件被激活时调用,在组件第一次渲染时也会被调用,之后每次keep-alive激活时被调用

deactivated:在组件被停用时调用

注意:

只有组件被 keep-alive 包裹时,这两个生命周期才会被调用,如果作为正常组件使用,是不会被调用,以及在 2.1.0 版本之后,使用 exclude 排除之后,就算被包裹在 keep-alive 中,这两个钩子依然不会被调用!另外在服务端渲染时此钩子也不会被调用的

什么时候获取数据?

当引入keep-alive的时候,页面第一次进入,钩子的触发顺序:

created==>mounted==》activated,

退出时触发deactivated

当再次进入时候,之触发activated

我们知道 keep-alive 之后页面模板第一次初始化解析变成 HTML 片段后,再次进入就不在重新解析而是读取内存中的数据。

只有当数据变化时,才使用 VirtualDOM 进行 diff 更新。所以,页面进入的数据获取应该在 activated 中也放一份。

数据下载完毕手动操作 DOM 的部分也应该在activated中执行才会生效。

所以,应该 activated 中留一份数据获取的代码,或者不要 created 部分,直接将 created 中的代码转移到 activated 中

实际应用:

如果未使用keep-alive组件,则在页面回退时会诚信渲染页面,触发created钩子,使用体验性不好

主要的使用场景就有:菜单存在多级关系【首页–》列表页–》详情页】

从首页跳转列表页面时,列表页面组件重新渲染;

当从详情页面返回列表页面时,列表组件缓存,不会重新请求数据

// app.vue
<template>
  <div id="app">
    <keep-alive :include="keepAliveInclude">
      <router-view/>
    </keep-alive>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name:'home',
  computed:{
    ...mapGetters([
      'keepAliveInclude',
    ])
  },
}
</script>

store 中对 keepAliveInclude 的状态更新保存

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    // keepAlive缓存组件
    keepAliveInclude:[],
  },
  getters:{
    keepAliveInclude: state => state.keepAliveInclude,
  },
  mutations: {
    SET_KEEPALIVEINCLUDE:(state, keepAliveInclude) => {
      state.keepAliveInclude = keepAliveInclude;
    }
  },
  actions: {
    setKeepAliveInclude({ commit }, keepAliveInclude){
      commit("SET_KEEPALIVEINCLUDE", keepAliveInclude)
    },
  },
})

需要进行缓存的页面 list.vue

<template>
  <div>
    <button @click="goHome">首页</button>
    <button @click="goDetail">详情</button>
    列表: <input type="text" v-model="inputVal">
  </div>
</template>
<script>
export default {
  name:'list',
  data(){
    return {
      inputVal:'',
    }
  },
  methods:{
    goDetail(){
      this.$router.push('./detail')
    },
    goHome(){
      this.$router.push('./home')
    }
  },
  beforeRouteLeave (to, from, next) {
    if(to.name == 'detail'){
      this.$store.dispatch('setKeepAliveInclude',['list'])
    }else{
      this.$store.dispatch('setKeepAliveInclude',[])
    }
    // next();
    setTimeout(() => { next(); }, 10); // next()需用定时器包裹,否则多次切换无法缓存
  }
}
</script>


相关文章
|
4月前
|
存储 缓存 JavaScript
|
9月前
|
缓存 JavaScript UED
|
11月前
|
缓存
Kepp-alive的实际运用场景(1)
Kepp-alive的实际运用场景(1)
|
11月前
|
网络协议
阿里一面:TCP 的 Keepalive 和 HTTP 的 Keep-Alive 是一个东西吗?
大致问题是,TCP 的 Keepalive 和 HTTP 的 Keep-Alive 是一个东西吗? 这是个好问题,应该有不少人都会搞混,因为这两个东西看上去太像了,很容易误以为是同一个东西。 事实上,这两个完全是两样不同东西,实现的层面也不同:
|
运维 网络协议 网络安全
Closed socket connection for client /39.103.162.230:56100 (no session established for client)
Closed socket connection for client /39.103.162.230:56100 (no session established for client)
341 0
Closed socket connection for client /39.103.162.230:56100 (no session established for client)
|
SQL 应用服务中间件 Linux
HTTP/2 504 Gateway Timeout 36369ms
HTTP/2 504 Gateway Timeout 36369ms
457 0
HTTP/2 504 Gateway Timeout 36369ms
|
缓存 JavaScript 开发者
keep-alive如何保持组件状态(上)
keep-alive的设计初衷: 有些业务场景需要根据不同的判断条件,动态地在多个组件之间切换。频繁的组件切换会导致组件反复渲染,如果组件包含有大量的逻辑和dom节点,极易造成性能问题。其次,切换后组件的状态也会完全丢失。keep-alive的设计初衷就是为了保持组件的状态,避免组件的重复渲染。
|
缓存 JavaScript
keep-alive如何保持组件状态(下)
keep-alive的设计初衷: 有些业务场景需要根据不同的判断条件,动态地在多个组件之间切换。频繁的组件切换会导致组件反复渲染,如果组件包含有大量的逻辑和dom节点,极易造成性能问题。其次,切换后组件的状态也会完全丢失。keep-alive的设计初衷就是为了保持组件的状态,避免组件的重复渲染。
|
网络协议 Go
客户端禁用Keep-Alive, 服务端开启Keep-Alive,会怎么样?
最近部署的web程序,服务器上出现不少time_wait的tcp连接状态,占用了tcp端口,花费几天时间排查。
客户端禁用Keep-Alive, 服务端开启Keep-Alive,会怎么样?