commit('setText', newText);
}
},
mutations: {
setText: (state, newText) => {
state.text = newText;
}
}
}
}
})
针对这个store,我们改写我们上一章节的组件
<template>
<div>
<h1>{{title}}</h1>
<span>{{text}}<span>
<button @click="setText">按钮</button>
</div>
</template><script>
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import { namespace } from 'vuex-class';
const fooModule = namespace('foo');
@Component
export default class Demo extends Vue {
@fooModule.State('text') text;
@fooModule.Action('setTextAction') setTextAction;
@Prop({type: String, default: 'Vue Demo'}) title;
@Watch('title')
titleChange(newTitle, oldTitle) {
console.log(`标题从 ${oldTile} 变为了 ${newTitle}`)
}
setText(e) {
this.setTextAction('点击了按钮');
}
}
</script>
这里可以发现,store声明了一个foo模块,然后在使用的时候从store中取出了foo模块,然后使用装饰器的形式将state和action注入到组件中,我们就可以省去dispatch的代码,让语法糖帮我们dispatch。这样的代码,看起来更贴切与面向对象。。。好吧,我承认这个代码越写越像Java了。
然而,之前的我并不是使用Redux开发React的,而是Mobx,所以这种 dispatch -> action -> matation -> state 的形式对我来说也不是很爽,我还是更喜欢把状态管理也以class的形式去编写,这个时候我又找了另外一个包vuex-module-decorators来改写我的store.module。
下面我们改写上面的store:
import Vuex from 'vuex';
import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators';@Module
class foo extends VuexModule {
text = 'hello world'
@Mutation
setText(text) {
this.text = text;
}
@Action({ commit: 'setText' })
setTextAction(text) {
return text;
}
}
const store = new Vuex.Store({
modules: {
foo: foo
})
export default store;
这样,我们的项目准备基本上完毕了,把Vue组件和Vuex状态管理以class的形式来编写。大概是我觉得es5的写法显得不太优雅吧,没有es6的写法那么高端。
结束
class语法和装饰器decorators语法都是ES6的提案,都带给了前端不一样的编程体验,大概也是前端的一个比较大的革命吧,我们应该拥抱这样的革命变化。










