vue中 keep-alive 組件的作用


原文地址


在vue項目中,難免會有列表頁面或者搜索結果列表頁面,點擊某個結果之后,返回回來時,如果不對結果頁面進行緩存,那么返回列表頁面的時候會回到初始狀態,但是我們想要的結果是返回時這個頁面還是之前搜索的結果列表,這時候就需要用到vue的keep-alive技術了.

keep-alive 簡介

keep-alive 是 Vue 內置的一個組件,可以使被包含的組件保留狀態,或避免重新渲染。
用法也很簡單:

<keep-alive>
  <component>
    <!-- 該組件將被緩存! -->
  </component>
</keep-alive>

props

  • include - 字符串或正則表達,只有匹配的組件會被緩存
  • exclude - 字符串或正則表達式,任何匹配的組件都不會被緩存
 
// 組件 a
export default {
  name: 'a',
  data () {
    return {}
  }
}
 
<keep-alive include="a">
  <component>
    <!-- name 為 a 的組件將被緩存! -->
  </component>
</keep-alive>可以保留它的狀態或避免重新渲染
<keep-alive exclude="a">
  <component>
    <!-- 除了 name 為 a 的組件都將被緩存! -->
  </component>
</keep-alive>可以保留它的狀態或避免重新渲染

但實際項目中,需要配合vue-router共同使用.

router-view 也是一個組件,如果直接被包在 keep-alive 里面,所有路徑匹配到的視圖組件都會被緩存:

<keep-alive>
    <router-view>
        <!-- 所有路徑匹配到的視圖組件都會被緩存! -->
    </router-view>
</keep-alive>

如果只想 router-view 里面某個組件被緩存,怎么辦?

增加 router.meta 屬性

 
// routes 配置
export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      keepAlive: true // 需要被緩存
    }
  }, {
    path: '/:id',
    name: 'edit',
    component: Edit,
    meta: {
      keepAlive: false // 不需要被緩存
    }
  }
]
 
 
<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- 這里是會被緩存的視圖組件,比如 Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- 這里是不被緩存的視圖組件,比如 Edit! -->
</router-view>

返回目錄


免責聲明!

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



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