在typescript里面使用vuex去做状态管理,其实跟js没什么区别,很难去拓展一些ts的特性,也达不到使用ts来优化项目体验的目的。虽然有一个强行把vuex转成ts的插件,但是太过于勉强,满屏的装饰器,看起来头皮发麻,而且组件里面使用也不太友好。所以就去翻了翻源码,把里面一些复杂的东西都去掉了,使用起来非常简单,使用js开发的同学也适用,请耐心往下看,如果你想摆脱vuex的束缚,不妨可以尝试以下。
安装
npm/cnpm install vue-lazy-store --save / yarn add vue-lazy-store
使用/Use
使用方法跟vuex类似,基本可以无缝切换.
store-ts
// src/store/index
import VueLazy from 'vue-lazy-store';
Vue.use(VueLazy);
class Text1 {
public count: number = 0;
public add(): number {
return count ++;
}
}
class BaseStore extends VueLazy.Store {
public text1: Text1;
public constructor() {
super();
this.text1 = new Text1();
// 请在最后面激活store / Activate store at the end
this.init();
}
}
// ssr
export default BaseStore;
// csr
export default new BaseStore();
declare module 'vue/types/vue' {
interface Vue {
$store: BaseStore;
}
}
declare module 'vue/types/options' {
interface ComponentOptions<V extends Vue> {
store?: BaseStore;
}
}
store-js
import Vue from "vue";
import VueLazy from "vue-lazy-store";
Vue.use(VueLazy);
const text1 = {
count: 0,
add() {
this.count++;
}
}
const store = new VueLazy.Store({
text1
});
store.init();
export default store;
.vue-ts
// support ts
import { Vue, Component, Watch } from 'vue-property-decorator';
@Component<LocalVue>({})
export default class LocalVue extends Vue {
public get text1 () {
return this.$store.text1;
}
public get count() {
return this.text1.count; // 0
}
public mounted() {
this.text1.add();
console.log(this.count); // 1;
}
}
.vue-js
computed: {
text1() {
return this.$store.text1;
},
count() {
return this.text1.count;
}
},
mounted() {
this.text1.add();
console.log(this.count); // 1;
}
ssr客户端接管状态
if (window.__INITIAL_STATE__) {
store.replace(window.__INITIAL_STATE__);
}
tips
状态变更上不像vuex那样严谨,需要commit状态为true时,才能更新。但是使用起来非常简单,
而且支持class写,进而完全支持ts,欢迎进一步完善。
之前想好的easy,simple之类的词语,一律用不了,那就不如叫它懒人store吧!
example
github地址
vue-lazy-store
感兴趣的同学欢迎start,也欢迎提出意见加以完善。
虽然vuex看起来比较笨重,但是在数据变更方面做的比较严谨,各方面也是比较完善。而vue-lazy-store呢,把所有的枷锁都去掉了,就需要开发者心中那把无形的枷锁,虽然这样可以直接去修改状态里面的属性,但是建议所有的属性修改必须由store向外提供方法去修改,而不是外界直接修改store里的属性值。本来就是一个状态集中管理的概念,所以大部分的操作,建议还是有store做好一切之后,再往外暴露成型的数据源。