vue中keep-alive 前進後退時頁面數據緩存和刷新問題

keep-alive用法:vue

一、在app.vue中定義keep-aliv緩存

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

二、在路由文件router.js中,定義meta信息session

{
  path: '/space4',
  name: 'space4',
  component: () => import( './components/workspace/space4.vue'),
  meta: {
    isUseCache: false, // 默認不緩存
    keepAlive: true,
  }
}

三、列表頁的activated鉤子app

activated() {
    if(!this.$route.meta.isUseCache){ //isUseCache 時添加中router中的元信息,判讀是否要緩存
      this.contactList = [] //清空原有數據
      this.contactDisplay() // 從新加載
    }
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    contactDisplay() {
      this.contactListGet = JSON.parse(sessionStorage.getItem('contact-item'))
      let personal = this.contactListGet
      let i = 0
      for(i in personal) {
        // let surname = personal[i].substring(0,1)
        let surname = personal[i].substring(personal[i].length-2)
        this.contactList.push({'surname': surname, name: personal[i]})
      }
      console.log('contactList', this.contactList)
    }
  }

四、詳細頁面 beforeRouteLeave的鉤子函數函數

 beforeRouteLeave(to, from, next){
    // 列表頁面跳轉到 詳情頁時,設置須要緩存
    if(to.name=='spaceContact'){
      from.meta.isUseCache = true
    }
    next()
  }

 

vue鉤子函數: post

設置了keepAlive緩存的組件:      this

    第一次進入:beforeRouterEnter ->created->…->activated->…->deactivated        spa

  後續進入時:beforeRouterEnter ->activated->deactivated 能夠看出,只有第一次進入該組件時,纔會走created鉤子,而須要緩存的組件中activated是每次都會走的鉤子函數。因此,咱們要在這個鉤子裏面去判斷,當前組件是須要使用緩存的數據仍是從新刷新獲取數據。code

【參考文章】component

相關文章
相關標籤/搜索