vue功能实现二:前进刷新页面后退进入缓存页面

在实际开发中发现之前的方法存在BUG,即如果发生A->B,B->C,C->A,A->B,如果B页面是个列表页就会存在问题,因为B页面的状态没有还原,导致加载的数据和展示有问题,故增加了私有方法_isInitPage和状态isInitPage,去掉以前的isInitPage原型方法,并做了进一步优化,目前在项目中运行良好。全部的,请看https://www.jianshu.com/p/93281f5c2b38

  • 添加state
const state = {
   cacheComponents: {}, // 已经缓存的页面组件
}
  • 创建mutation方法
// 是否需要清已缓存的页面组件标识
    [REMOVE_CATCHE_PAGE](state) {
        state.cacheComponents = { };
    }
  • 在入口处设置缓存组件
<template>
    <div id="app">
        <transition>
          <keep-alive>
            <router-view class='router-view' v-if="$route.meta.keepAlive && isRouterAlive"></router-view>
          </keep-alive>
        </transition>
        <transition>
          <router-view class='router-view' v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
        </transition>
    </div>
</template>
  • 在入口文件main.js处判断前进还是后退,及缓存组件
import Vue from 'vue'
import router from 'router'
import store from 'store'

let cacheComponents = {};
store.commit("SAVE_CATCH_COMPONENTS", cacheComponents); // 刷新就重置,防止刷新后退无法执行初始化

// 需要为Vue对象增加三个原型方法和一个私有方法
// 重新定义路由切换,配合页面切换动画效果
1. 增加后退方法(项目中统一使用该方法)
Vue.prototype.$pageBack = (index, path, params) => {
  store.commit('UPDATE_DIRECTION', {direction: 'reverse'});
  if(path) {
    // 允许后退到指定的页面
    router.push({path: path, query: params});
  } else {
    index = index || 1;
    let currentName= router.history.current.name;
    let firstPage = sessionStorage.getItem('firstPage');
    // 防止后退退出应用
    if(firstPage == currentName && currentName != 'index'){
        sessionStorage.setItem('firstPage', "index");
        router.push({path:'/'})
        return false
    }else{
        router.go(-index)
    }
  }
}
2. 增加前进方法(项目中统一使用该方法)
Vue.prototype.$pageInit = (path, params, isReplace) => {
  store.commit('UPDATE_DIRECTION', {direction: 'forward'});
  params = params || {};
  if(isReplace) {
    router.replace({
      path: path,
      query: params
    });
  } else {
    router.push({
      path: path,
      query: params
    });
  }
}

3.去除组件缓存中的某个标识(如果需要某个页面组件重新初始化数据,可执行该方法,flag可传入多个name,使用逗号分隔)
Vue.prototype.removeCacheComponentFlag = (flag) => {
  let cacheComponents = store.state.cacheComponents;
  const arr = flag ? flag.split(',') : [];
  arr.map((name, index) => {
    delete cacheComponents[flag];
  })
  store.commit("SAVE_CATCH_COMPONENTS", cacheComponents);
}

4.是否需初始化页面(将状态isInitPage储存起来)
Vue.prototype._isInitPage = (to) => {
  let cacheComponents = store.state.cacheComponents;
  let direction = store.state.direction;
  let name = to.name;
  let keepAlive = to.meta.keepAlive;
  if(direction == 'forward' || (direction == 'reverse' && !cacheComponents[name])) {
    store.commit("CHANGE_STATE", {"isInitPage": true});
  } else {
    store.commit("CHANGE_STATE", {"isInitPage": false});
  }
  // 储存已缓存组件标识
  if(keepAlive && !cacheComponents[name]) {
    cacheComponents[name] = true;
    store.commit("SAVE_CATCH_COMPONENTS", cacheComponents);
  }
}
5.在router.beforeEach函数上处理,判断即将要跳转的页面是否需要重新初始化
router.beforeEach((to, from, next) => {
     // 在next之前执行
    // 判断下一页是否需要重新初始化
    window.vm && window.vm._isInitPage(to);
})

6. 增加公共方法执行
// 增加mixin.js文件(可以分别针对全局和局部封装对应的mixin)
export const mixin = {
  activated() {
    if(this.isInitPage) {
        // 重新初始化数据
       Object.assign(this.$data, this.$options.data());
        
        // 需要重新执行初始化
        // 在methods中增加init方法
        if(typeof(this.init) == 'function') {
            this.init();
        }
    } else {
        // 不需要重新执行初始化,但允许操作方法
        // 在methods中增加noLoad方法
        if(typeof(this.noLoad) == 'function') {
            this.noLoad();
        }
    }
  },
  mounted() {
    // 兼容处理keepAlive为false的情况
    if(!this.$route.meta.keepAlive) {
        if(typeof(this.init) == 'function') {
            this.init();
        }
    }
  },
 computed: {
    ...mapState([
      'isLogin',
      'lc_client_no',
      'user_id',
      'userInfo',
      'isInitPage'
    ]),
    constants(){
      return constants;
    }
  },
  methods: {
    ...mapMutations([
      'CHANGE_STATE'
    ])
  }
}

// 在页面组件中引入mixin(其实可全局引入)
import {mixin} from '@/assets/mixin.js'
export default {
    mixins: [mixin],
    ....
}
  • 使用该方法需要注意以下几点
1. 配置路由时,尽可能都设置为keepAlive为true,统一化处理,也为后期组件开发带来一定的便利性,如可以直接抛弃created/mounted方法
2. 由于设置为缓存页面,故封装的子组件(可以视为所有非页面组件的其它组件),最好用监听父组件传来的一个属性方法来控制页面初始化。如监听isLoad属性,一旦变为true则初始化
3.如果后退需要刷新数据的,可以通过设置状态值,然后再noLoad方法中处理重新加载数据,或者处理状态值中的cacheComponents,去掉返回页对应的标识(需要知道返回哪一页的前提)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容