zoukankan      html  css  js  c++  java
  • Vue 的 keep-alive 的作用是什么

    keep-alive可以在组件切换时,保存其包裹的组件的状态,使其不被销毁,防止多次渲染。其拥有两个独立的生命周期钩子函数 actived 和 deactived,使用keep-alive包裹的组件在切换时不会被销毁,而是缓存到内存中并执行 deactived 钩子函数,命中缓存渲染后会执行 actived 钩子函数。

    props

    • include - 字符串或正则表达,只有匹配的组件会被缓存
    • exclude - 字符串或正则表达式,任何匹配的组件都不会被缓存
    1.  
      // 组件 a
    2.  
      export default {
    3.  
      name: 'a',
    4.  
      data () {
    5.  
      return {}
    6.  
      }
    7.  
      }
    1.  
      <keep-alive include="a">
    2.  
      <component>
    3.  
      <!-- name 为 a 的组件将被缓存! -->
    4.  
      </component>
    5.  
      </keep-alive>可以保留它的状态或避免重新渲染
    1.  
      <keep-alive exclude="a">
    2.  
      <component>
    3.  
      <!-- 除了 name 为 a 的组件都将被缓存! -->
    4.  
      </component>
    5.  
      </keep-alive>可以保留它的状态或避免重新渲染

    但实际项目中,需要配合vue-router共同使用

    App.vue

    1.  
      <template>
    2.  
      <div id="app">
    3.  
      <!-- 路由占位符 -->
    4.  
      <!-- <router-view></router-view> -->
    5.  
      <keep-alive>
    6.  
      <router-view v-if="$route.meta.keepAlive">
    7.  
      <!-- 这里是会被缓存的视图组件 -->
    8.  
      </router-view>
    9.  
      </keep-alive>
    10.  
       
    11.  
      <router-view v-if="!$route.meta.keepAlive">
    12.  
      <!-- 这里是不被缓存的视图组件 -->
    13.  
      </router-view>
    14.  
      </div>
    15.  
      </template>

    router -> index.js

    1.  
      const routes = [
    2.  
      { path: '/', redirect: '/index' },
    3.  
      { path: '/', redirect: '/home' },
    4.  
      {
    5.  
      path: '/home',
    6.  
      component: HomeLayout,
    7.  
      children: [
    8.  
      {
    9.  
      path: '/home',
    10.  
      component: Home
    11.  
      },
    12.  
      {
    13.  
      path: '/workingCondition',
    14.  
      component: () =>
    15.  
      import(
    16.  
      /*webpackChunkName:"workingCondition"*/ '../views/workingCondition/index.vue'
    17.  
      ),
    18.  
      meta: {
    19.  
      keepAlive: true // 需要被缓存
    20.  
      }
    21.  
      }
    22.  
      ]
    23.  
      },
    24.  
      {
    25.  
      path: '/reportView',
    26.  
      component: () => import('../views/other/reportView.vue')
    27.  
      },
    28.  
      {
    29.  
      path: '/todo',
    30.  
      component: () => import(/*webpackChunkName:"ToDo"*/ '../views/ToDo.vue'),
    31.  
      meta: {
    32.  
      keepAlive: true // 需要被缓存
    33.  
      }
    34.  
      }
    35.  
      ]

    转:https://blog.csdn.net/qq_37548296/article/details/110798890

  • 相关阅读:
    渲染管线中的顶点变换
    导入图片时设置默认格式
    查找丢失组件的预制体
    移动到目标点的方法
    关于material和sharedMaterial的问题
    代码创建动画状态机
    设计模式学习笔记--访问者模式
    .net core 基于Dapper 的分库分表开源框架(core-data)
    .Net 微服务架构技术栈的那些事
    Asp.Net Core 中IdentityServer4 实战之角色授权详解
  • 原文地址:https://www.cnblogs.com/ygyy/p/14691924.html
Copyright © 2011-2022 走看看