vue之keep-alive的使用

keep-alive:是vue內置的一個組件,能夠使被包含的組件保留狀態或避免從新渲染。有兩個生命週期函數:activated、deachtivated。在vue 2.1.0版本後新增了兩個屬性:include與exclude。vue

 

生命週期函數(在服務端渲染時,如下兩個鉤子函數不會被調用)正則表達式

  activated:在 keep-alive 組件激活是調用。若是每次進入頁面的時候獲取最新的數據,須要在activated階段獲取數據,承擔原來created鉤子函數中獲取數據的任務vue-router

  deachitivated:在 keep-alive 組件停用時調用。緩存

 

屬性函數

  include:spa

    類型:字符串(include="") 或 表達式(使用 v-bind:include="")code

    做用:只有名稱匹配的組件纔會被緩存component

  exclude(優先級 > include):router

    類型:字符串(exclude="") 或 表達式(使用 v-bind:exclude="")blog

    做用:任何名稱匹配的組件都不會被緩存

  max:

    類型:Number

    做用:最多能夠魂村多少組件實例

 

組件緩存實例

// 新增一個組件:
export default {
  name: 'test-keep-alive',
  data () {
    return {
        includedComponents: "test-keep-alive"
    }
  }
}


// 實例:
<keep-alive include="abc">
    <!-- 將緩存組件名 = abc 的組件 -->
    <component></component>
</keep-alive>

<keep-alive include="a,b">
   <!-- 結合動態組件,將緩存name爲a或b的組件 -->
    <component :is="a"></component>
</keep-alive>


<!-- 使用正則表達式,需使用v-bind -->
<keep-alive :include="/a|b/">
  <component :is="view"></component>
</keep-alive>

<!-- 動態判斷 -->
<keep-alive :include="includedComponents">
  <router-view></router-view>
</keep-alive>

<keep-alive exclude="test-keep-alive">
  <!-- 將不緩存name爲test-keep-alive的組件 -->
  <component></component>
</keep-alive>

 

頁面緩存實例(結合 vue-router)

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


//  在router的index.js中配置 meta 元信息
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello,
      meta: {
        keepAlive: false // 不須要緩存
      }
    },
    {
      path: '/page1',
      name: 'Page1',
      component: Page1,
      meta: {
        keepAlive: true // 須要被緩存
      }
    }
  ]
})

 

 

生於憂患,死於安樂

相關文章
相關標籤/搜索