天天看點

vue vuex+keep-alive進階用法(靈活緩存頁面,主要是移動端)

注意:每個頁面都要添加name,name:"頁面名稱',不然不起作用

1、在App.vue中,編寫如下代碼

<template>
    <div id="app">
        <!-- include 需要緩存的元件 -->
        <keep-alive :include="includeList">
            <router-view />
        </keep-alive>

    </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
    data(){
        return{
        }    
    },
    computed: {
        ...mapState(['includeList'])
    },
}
           

2、在store.js中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    includeList: ['Home', 'Center', 'Cart'], //初始化緩存頁面,一般來說就用tabbar底部的導航,自定義添加
  },
  mutations: {
    //插入緩存數組
    setInclude(state, data) {
      var index = state.includeList.indexOf(data);
      if (index == -1) {
        state.includeList.push(data)
      }
    },
    //删除對應緩存字段
    del_include(state, data) {
      var index = state.includeList.indexOf(data);
      if (index > -1) {
        state.includeList.splice(index, 1)
      }
    },
  },

  actions: {
  },
  modules: {
  }
})
           

3、tabbar頁面使用,主要是底部導航那幾個一級頁面

export default {
    name:'Home',

    beforeRouteEnter(to, from, next) {
        next(vm => {
            document.querySelector('body').setAttribute('style', 'background-color:#f6f6f6');
        })
    },
    beforeRouteLeave(to, from, next) {
        if (from.name === 'Home') {
            this.$store.commit('setInclude', 'Home')
        } 
        document.querySelector('body').removeAttribute('style')
        next()
    },
    
    created(){
        //初始化一些資料
    },

    //keep-alive緩存,替代created()執行,首次不執行,之後隻要緩存生效了每次都會執行。重新整理時created與activated都會執行
    activated(){
        //要執行的操作
    },
    
    //解除安裝
    deactivated() {
        
    },
}
           

4、非tabbar頁面使用

export default {
    name:'list',

    beforeRouteEnter(to, from, next) {
        next(vm => {
            document.querySelector('body').setAttribute('style', 'background-color:#f6f6f6');
        })
    },
    beforeRouteLeave(to, from, next) {
        //to.path 指要跳轉的頁面路徑,比如從清單頁跳轉到詳情頁
        if (to.path === '/listDetail') {
			this.$store.commit('setInclude', 'list')
		} else {
			this.$store.commit('del_include', 'list')
		}
		document.querySelector('body').removeAttribute('style')
		next()
    },
    created(){
        //初始化一些資料
    },

    //keep-alive緩存,替代created()執行,首次不執行,之後隻要緩存生效了每次都會執行。重新整理時created與activated都會執行
    activated(){
        //要執行的操作
    },
    
    //解除安裝
    deactivated() {
        
    },
}
           

這樣就可以了,親測有效,如果有哪些不清楚或疑問的在下方留言!