1. 程式人生 > 實用技巧 >【Vue】Re18 Router 第五部分(KeepAlive)

【Vue】Re18 Router 第五部分(KeepAlive)

一、KeepAlive概述

預設狀態下,使用者點選新的路由時,是訪問新的元件

那麼當前元件是會被銷燬的,然後建立新的元件物件出來

如果某些元件頻繁的使用,將造成記憶體空間浪費,也吃記憶體效能

所以需求是希望元件能被快取起來,不是立即銷燬

生命週期的建立函式create();和銷燬函式destory();都將反覆呼叫

二、使用

只需要把router-view做為keep-alive的子元素就行了

<template>
  <div id="app">
    <router-link to="/home" tag="button" >去首頁</router-link
> <router-link to="/about" tag="button" >去關於</router-link> <router-link :to="/user/+username" tag="button" >使用者管理</router-link> <router-link :to="ppp" tag="button" >profile</router-link> <!-- <button @click="toProfile" >profile</button>-->
<!-- <button @click="toHome">首頁</button>--> <!-- <button @click="toAbout">關於</button>--> <keep-alive> <router-view></router-view> </keep-alive> <p> <button @click="getRouterInstance">獲取Router物件</button
> <button @click="getCurrentRouteInstance">獲取Route物件</button> </p> </div> </template>

如果元件的週期不再銷燬,那麼生命狀態則發生了改變

在訪問時是被啟用的狀態

如果離開了元件時,則是非啟用狀態

對應了兩個生命週期函式:

activated () {
  // todo ...  
}
deactivated () {
  // todo ...  
}

注意!!!上述的函式僅對keep-alive處理的元件有效

三、關於重定向路由BUG問題

/router/index.js

父級路由

  /* 重定向首頁路由配置 */
  {
    path : '', /* 預設值預設指向 '/' */
    redirect : '/home',
  },

子級路由

    children : [ /* 設定子路由 */
      {
        path : '', /* 這個預設預設/home */
        redirect : 'news',
      },

重定向home的時候觸發子路由的重定向

向下繼續重定向到/home/news

解決方案:

移除子路由的重定向,在元件初始化時重定向一次,後續不再重定向

還有要記錄使用者之前訪問的元件的路由,回到之前的父元件時訪問的子元件

<template>
  <div>
    <h3>這是首頁Home元件</h3>
    <p>
      首頁Home元件的內容 <br>
      <router-link to="/home/news">新聞列表</router-link>
      <router-link to="/home/messages">訊息列表</router-link>
    </p>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Home",
  created() {

  },
  data () {
    return {
      path : '/home/news'
    }
  },
  activated() {
    this.$router.push(this.path);
  },
  // deactivated() {
  //   this.path = this.$route.path;
  // }
  beforeRouteLeave (to, from, next) {
    this.path = this.$route.path;
    next();
  }
}
</script>

<style scoped>

</style>

四、Keep-Alive的兩個屬性

    <keep-alive
      include="Home,Message"
      exclude="News,Profile"
    >
      <router-view></router-view>
    </keep-alive>

include表示需要快取在裡面的元件

exclude表示排除,不要快取的元件

預設是使用正則表示式,符合正則規則的元件名稱,就會把該元件選中

也可以是直接寫元件的名稱表示,注意不要有空格

元件的名稱就是這個:

用途主要是為了排除特定不需要快取的元件,一般需要快取的不需要填寫屬性表示了