好久没写干货了,趁这次公司升级系统,抽空写下。目前本人研究出该方法一段时间了,暂没发现有坑,有坑希望能人指出
重载页面(最简单方法,直接在入口文件APP.vue处处理)
全局引用,不需要针对个别页面处理,简化开发工作量
- 添加state
const state = {
isReload: false, // 是否需要重加载页面组件
}
- 创建mutation方法
// 是否需要重载
[IS_RELOAD](state) {
state.isReload = !state.isReload;
}
- 在入口处设置激活组件
<router-view class='router-view' v-if="isRouterAlive"></router-view>
// 设置data数据
isRouterAlive: true
// watch监听isReload状态
isReload(value) {
// 一旦发生变化则重载组件
this.isRouterAlive = false;
this.$nextTick(() => {
this.isRouterAlive = true;
})
}
- 通过改变isReload状态来实现重载页面
this.$store.commit('IS_RELOAD');
实现前进刷新后退缓存
vue本身存在BUG,一旦使用缓存且$destroy方法,该页面每次打开都会重新生成,会不断叠加生成,失去了缓存的效果,后来经过查阅资料后,再三思考,既然vue支持v-if来切换重载页面,那意味着清理缓存也一样可以。最后发现效果还不错,清空了所有页面的同时,如果不发生跳转,也生成了新的页面,中间无过渡动画效果,但该处理方式估计坑挺多的,后放弃该方法,转而采用以下方式:
- 添加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,去掉返回页对应的标识(需要知道返回哪一页的前提)
缓存页与非缓存页动画效果乱问题
- 在入口文件app.vue处理
<template>
<div id="app" v-if="!isRemoveCatchPage">
<transition :name="transitionName"
@before-leave="beforeLeave"
@before-enter="beforeEnter">
<keep-alive>
<router-view class='router-view' v-if="$route.meta.keepAlive && isRouterAlive"></router-view>
</keep-alive>
</transition>
<transition :name="transitionName"
@before-leave="beforeLeave"
@before-enter="beforeEnter">
<router-view class='router-view' v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
</transition>
</div>
</template>
// 设置data数据
isRemoveCatchPage: false,
transitionName : 'pop-' + (this.direction === 'forward' ? 'in' : 'out')
// watch监听路由状态
$route(to, from) {
to = to || {};
if (to.name == 'index') {
this.transitionName = 'fade'
} else {
this.transitionName = 'pop-' + (this.direction === 'forward' ? 'in' : 'out');
}
}
// 添加方法
beforeEnter: function (el) {
el.removeAttribute("data-animation");
},
beforeLeave: function (el) {
el.removeAttribute("data-animation");
if(this.direction == 'reverse') {
// 返回,添加一个比重高的样式替换缓存的样式
el.setAttribute("data-animation", this.transitionName + "-leave-active");
} else if(this.direction == 'forward') {
// 前进,添加一个比重高的样式替换缓存的样式
el.setAttribute("data-animation", this.transitionName + "-leave-active");
}
}
- 通过样式的比重来解决动画效果错乱
提供完整的app.vue文件
<template>
<div id="app" v-if="!isRemoveCatchPage">
<transition :name="transitionName"
@before-leave="beforeLeave"
@before-enter="beforeEnter">
<keep-alive>
<router-view class='router-view' v-if="$route.meta.keepAlive && isRouterAlive"></router-view>
</keep-alive>
</transition>
<transition :name="transitionName"
@before-leave="beforeLeave"
@before-enter="beforeEnter">
<router-view class='router-view' v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
<!-- <router-view class='router-view' v-if="isRouterAlive"></router-view> -->
</transition>
</div>
</template>
<script>
import { mapState } from 'vuex'
import Vue from "vue"
export default {
data(){
return{
name: "测试话说",
isRouterAlive: true,
isRemoveCatchPage: false,
transitionName : 'pop-' + (this.direction === 'forward' ? 'in' : 'out')
}
},
mounted(){
},
computed:{
...mapState([
'direction',
'isReload',
'is_remove_catche_page'
])
},
methods: {
beforeEnter: function (el) {
el.removeAttribute("data-animation");
},
beforeLeave: function (el) {
el.removeAttribute("data-animation");
if(this.direction == 'reverse') {
// 返回,添加一个比重高的样式替换缓存的样式
el.setAttribute("data-animation", this.transitionName + "-leave-active");
} else if(this.direction == 'forward') {
// 前进,添加一个比重高的样式替换缓存的样式
el.setAttribute("data-animation", this.transitionName + "-leave-active");
}
},
},
watch: {
$route(to, from) {
to = to || {};
if (to.name == 'index') {
this.transitionName = 'fade'
} else {
this.transitionName = 'pop-' + (this.direction === 'forward' ? 'in' : 'out');
}
},
isReload(value) {
// 一旦发生变化则重载组件
this.isRouterAlive = false;
this.$nextTick(() => {
this.isRouterAlive = true;
})
},
is_remove_catche_page(value) {
// 一旦发生变化则重载组件
this.isRemoveCatchPage = true;
this.$nextTick(() => {
this.isRemoveCatchPage = false;
})
}
}
}
</script>
<style>
#app{
height: 100%;
width: 100%;
position: relative;
overflow: hidden;
}
.pop-out-enter-active,
.pop-out-leave-active,
.pop-in-enter-active,
.pop-in-leave-active {
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
overflow-x: hidden;
overflow-y: auto;
will-change: opacity,transform;
transition: all 0.3s;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-active {
opacity: 0;
}
.pop-out-enter {
opacity: 0;
transform: translate3d(-100%, 0, 0);
}
body [data-animation = 'pop-out-leave-active'], .pop-out-leave-active {
opacity: 0;
transform: translate3d(100%, 0, 0);
}
.pop-in-enter {
opacity: 0;
transform: translate3d(100%, 0, 0);
}
body [data-animation = 'pop-in-leave-active'], .pop-in-leave-active {
opacity: 0;
transform: translate3d(-100%, 0, 0);
}
.vux-loading .weui-toast{
top: 250px;
}
</style>