1.0.0 • Published 3 years ago
vuex-plugin-loadings v1.0.0
vuex-plugin-loadings
一个自动处理 vuex loading 状态的插件。
背景
在我们的 vue 项目中,经常有出现类似以下代码:
export default {
namespaced: true,
state: {
loading: false,
data: [],
},
actions: {
async getData({ state, commit }) {
commit('SET_LOADING', true);
try {
const resp = await Services.getData();
commit('SET_DATA', resp);
} catch (error) {
console.log('error', '\n', error);
} finally {
commit('SET_LOADING', false);
}
},
},
mutations: {
SET_LOADING(state: any, status: boolean) {
state.loading = status;
},
SET_DATA(state: any, data: any) {
state.data = data;
}
}
}
上述示例代码中,对于有异步数据处理的场景,我们一般会手动维护 loading 的状态,供页面中交互显示。对于规模小的项目,这没有什么问题。但如果我们的 action 比较多,每个 action 这样搞一遍的话,还都是比较繁琐的。
该插件借助 vuex 3.1.0 版本新增的 subscribeAction api,实现全局自动关联处理 loading 状态,解放你的双手,你值得拥有。
关于 subscribeAction api,详情可参考:https://vuex.vuejs.org/zh/api/#subscribeaction
安装
yarn add vuex-plugin-loadings
使用
1. 注册
import createLoadingPlugin from 'vuex-plugin-loadings';
Vue.use(Vuex);
export default new Vuex.Store({
plugins: [createLoadingPlugin()]
});
2. 引用
import Vue from 'vue';
import { mapState } from 'vuex';
@Component({
computed: {
...mapState({
loading: state => state[`LOADING`].effects[`module/actions`]
}),
},
})
export default class DemoComponent extends Vue {}
参数
当前 createLoadingPlugin 提供的初始化参数如下:
interface ILoadingInterface {
namespace?: string; // 命名空间,默认为 LOADING
exclude?: string[]; // Types 排除列表
}
联系
kanging@sensetime.com
1.0.0
3 years ago