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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM