vue中的keep-alive緩存

在開發vue項目時,咱們常常須要在各個組件之間進行切換,當咱們在A組件中寫了一些內容,或者保存了一些狀態的時候,切換到其餘組件,A組件的內容就消失了,這是什麼緣由呢?vue

咱們在A組件的生命週期created中打印一下:瀏覽器

created(){
    // eslint-disable-next-line no-console
    console.log("組件從新渲染了");
  },

而後咱們在瀏覽器中來回切換幾回組件,查看一下控制檯:
捕獲.PNG
能夠看出,每一次進行組件切換的時候,組件都會進行從新渲染,因此裏面的內容也會跟着消失,那麼咱們就會用到keep-alive來解決這個問題。緩存

keep的幾種使用方式

1.自定義想要緩存的組件iview

首先在App.vue中添加代碼:spa

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

這一段代碼的意思是:
當正在跳轉的組件的$route.meta.keepAlive爲true時,就將該組件加入緩存,不然不加入緩存。3d

而後在路由中找到咱們須要進行緩存的組件,設置meta.keepAlive的值爲trueeslint

path: '/',
    name: 'Home',
    component: Home,
    meta: {
        keepAlive: true
    }

此時當咱們在home組件表單中輸入123,而後點擊跳轉到其餘組件再回來的時候,咱們發現123仍然存在,生命週期也不會再從新打印了。code

咱們還能夠直接在路由守衛中進行keepAlive值的設置:component

beforeRouteLeave(to,from,next){
    to.meta.keepAlive = true;
    next();
  }

2.結合動態組件<component>使用router

<template>
  <div class="home">
  <keep-alive>
    <component v-if="iview" :is="view1"></component>
    <component v-if="!iview" :is="view2"></component>
  </keep-alive>
  <button @click="iview = !iview">切換子組件</button>
  </div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
import WorldHello from '@/components/WorldHello.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld,WorldHello
  },
  data(){
    return{
      iview:true,
      view1:HelloWorld,
      view2:WorldHello
    }
  }
}
</script>

這樣咱們在HelloWorld和WorldHello這兩個組件之間進行切換時候,兩個組件都會被緩存了。

注意:動態組件中才能夠使用,靜態組件是不能夠使用的,例以下面這種:

<keep-alive>
    <component is="view1"></component>
</keep-alive>
相關文章
相關標籤/搜索