• 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

  • 相关阅读:
    Mvaen系列第5篇:私服详解(本文内容来自 路人甲java)
    springmvc和springboot做分页查询
    maven详解4:仓库详解
    Maven系列3:详解maven解决依赖问题(该系列从 路人甲java 学习)
    maven学习2:安装、配置、mvn运行(本系列从 路人甲java 学习)
    maven学习系列1:maven入门
    日期格式转换
    springmvc、springboot配置静态资源
    反射
    java中运行python脚本
  • 原文地址:https://www.cnblogs.com/ygyy/p/14691924.html
Copyright © 2020-2023  润新知