在使用vuex时,如何更好的封装一些通用的交互效果呢,比如说每次ajax请求时开始时都会有一个处理中的动画,请求结束时动画消失,还有在点击某个 btn 进行保存数据时,在结果没有从服务端返回之前按钮是禁用的。
现在是写在 action 里,重复 dispatch 各种 mutation 处理这些效果,但这样会发现代码中夹杂着跟主业务无关的代码,这些代码是处理交互效果的,而且大部分交互效果是相同的。
特别是ajax请求是的载入动画的问题,我也纠结了好久,如果你是用jquery的ajax来请求数据,其实可以用ajax的全局函数
$(document).ajaxStart(() => {
NavbarActions.updateAjaxAnimation('fadeIn');
});
$(document).ajaxComplete(() => {
setTimeout(() => {
NavbarActions.updateAjaxAnimation('fadeOut');
}, 750);
});
只要一定义,无论在哪里发起ajax请求全会执行这两个全局方法
后来我在用vue改写项目的时候 用了vue-resource来请求API,但vue-resource没有类似全局函数,
所以我通过interceptors来实现
Vue.use(VueResource)
Vue.use(VueRouter)
Vue.http.interceptors.push({
request (request) {
updateAjaxAnimation(store, 'fadeIn')
return request
},
response (reponse) {
setTimeout(() => {
updateAjaxAnimation(store, 'fadeOut')
}, 750)
return reponse
}
})
附我的实践项目的全部源代码:
react版本:https://github.com/papersnake/newdenfaces-es6
vue重写版:https://github.com/papersnake/newdenfaces-vue