点击子元素跳转回退不丢失数据
src/store/store.js;
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
routeHistory: []
}
});
export default store;
src/router/router.js;
import Router from 'vue-router'
var routerInstance = new Router()
//开启routeHistory总线
routerInstance.beforeEach((to,form,next)=>{
store.state.routeHistory.push(to.fullPath);
next();
});
export default RouterInstance;
src/utils/routeHistoryUtil.js
import stroe from './store.js'
export default {
get: function(num=0) {
num = Math.floor(num) || 0;
const routeHistory = store.state.routeHistory;
let length = routeHistory.length;
if(length===0) {
return void(0);
}
num = (num+length) % length;
return routeHistory[num];
},
getLast:function() {
return this.get(-1);
},
getLentgh: function() {
return store.state.routeHistory.length;
}
}
src/app.vue
<template>
<div id="app">
// 是否使用keep-alive渲染
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</div>
</template>
src/page/demo.vue
<template>
<div class="demo"></div>
</template>
<script>
import routeHistoryUtil from '@/utils/routeHistoryUtil.js'
const defaultData = {
};
export default {
data() {
return {
...defaultData
}
}
activated() {
let totalFlag = true;
let fromPath,PfromPath,flag;
if(!routeHistoryUtil.getLength() < 3) {
//最后一条记录是自身
// 获取最后第二条记录
fromPath = routeHistoryUtil.get(-2);
// 获取最后第三条记录
PfromPath = routeHistoryUtil.get(-3);
// 判断上一条路径是否是我们期望的
flag = this.checkPath(fromPath);
// 判断上上条记录是否是自身
totalFlag = !flag || PfromPath !== this.$route.path;
}
// 如果上一条路径不在期望中或者上上条路径不是自身的话,重置初始数据
if (totalFlag) {
for (var attr in data) {
if (data.hasOwnProperty(attr)) {
this[attr] = data[attr];
}
}
}
// 初始化调用接口操作
this.getData();
}
}
</script>