Vuex作为vue中核心的状态管理组件,时常遇到编写繁琐的问题。是否我们可以通过一套方案就可以达到只定义数据结构而不需要写无数的mutation
getter
以及action
。
所以,原则上我们是让vuex变的更加轻量和简单。
Super-Vuex
Super-Vuex 能够帮你完成这些工作。我们先来看下简单的写法,是否能够满足你日常开发的需要。
数据:
// namespace: user
const store = {
name: 'evio',
age: 18,
contact: {
email: 'xxx@qq.com',
tel: 13000000000,
students: [
{ name: 'aaa', age: 20 }
]
}
};
调用:
this.$store.user.commit('age', 30);
this.$store.user.commit('contact.email', 'aaa@qq.com');
this.$store.user.commit('contact.tel', 13800000000);
this.$store.user.push('contact.students', { name: 'bbb', age: 21 }, { name: 'ccc', age: 22 });
this.$store.user.unshift('contact.students', { name: 'ddd', age: 23 });
this.$store.user.splice('contact.students', 1, 2);
如果按照我们的设计,整个Vuex将变成一个数据对象,我们可以通过一些方法直接操作它。让它的开发变的简便,同时,能够节省很多代码,使整个项目体积变小。
Super-Vuex
已帮你完成这些工作。当然,我们也需要自定义某些方法,这些都是支持的。
简单演示
创建ChildVuex实例,存储user数据
// ./store/user.js
import { ChildVuex } from "super-vuex";
// 'user'为命名空间
const child = new ChildVuex('user');
export default child;
child.value = {
name: 'evio',
age: 18,
students: [
{
name: 'yixianle',
age: 10
}
],
load: {
allow: true,
total: 100
}
};
可以创建多个,这里再创建一个ChildVuex实例,存储sub数据
// ./store/sub.js
import { ChildVuex } from "super-vuex";
// 'sub'为命名空间
const sub = new ChildVuex('sub');
export default sub;
sub.value = {
name: 'evio',
subs: [1,2,3,4],
isVip: false,
};
创建一个SuperVuex实例
// store.js
import { SuperVuex } from 'super-vuex';
// 两个vuex插件,vuexPromise和vuejsStorage
import vuexPromise from 'vuex-promise';
import vuejsStorage from 'vuejs-storage';
import UserStore from './store/user';
import Subs from './store/sub'
const Main = new SuperVuex();
Main.setModule(UserStore);
// 可以set多个module
Main.setModule(Subs);
// 在SuperVuex中使用插件
Main.setPlugin(vuexPromise, vuejsStorage);
export default Main.init();
在VUE中如何使用
<template>
...
</template>
<script>
import store from './store';
export default {
store: store,
name: "index",
methods: {
changeName() {
this.$store.user.commit('name', 'someone');
},
changeAllow() {
this.$store.user.commit('load.allow', false);
},
pushStudent() {
this.$store.user.push('students', {
name: 'huaping',
age: 300
});
},
pushSubs() {
this.$store.sub.push('subs', 10);
},
unshiftStudent() {
this.$store.user.unshift('students', {
name: 'huaping1',
age: 302
});
},
deleteStudent() {
this.$store.user.splice('students', 0, 1);
},
gets() {
this.$store.user.dispatch('load.data');
}
}
}
</script>
最后
某些简单的东西往往更能提高我们的开发效率,经过我在公司的实践,比如复杂的一些后台系统,super-vuex
就非常合适。欢迎issues和pr。