详解从react转职到vue开发的项目准备

2020-06-14 06:12:30易采站长站整理

onClick={this.clickHandler}
nativeOnClick={this.nativeClickHandler}
// other special top-level properties
class={{ foo: true, bar: false }}
style={{ color: 'red', fontSize: '14px' }}
key="key"
ref="ref"
// assign the `ref` is used on elements/components with v-for
refInFor
slot="slot">
</div>
)
}

但是,Vue的jsx语法无法支持Vue的内建指令,唯一的例外是v-show,该指令可以使用v-show={value}的语法。大多数指令都可以用编程方式实现,比如

v-if
就是一个三元表达式,
v-for
就是一个
array.map()
等。

如果是自定义指令,可以使用v-name={value}语法,但是该语法不支持指令的参数arguments和修饰器modifier。有以下两个解决方法:

将所有内容以一个对象传入,如:v-name={{ value, modifier: true }}
使用原生的vnode指令数据格式,如:


const directives = [
{ name: 'my-dir', value: 123, modifiers: { abc: true } }
]

return <div {...{ directives }}/>

那么,我们什么时候使用jsx,什么时候template呢?很明显,面对那么复杂多变的视图渲染,我们使用jsx语法更能得心应手,面对简单的视图,我们使用template能开发得更快。

状态管理

特性对比

针对状态管理,Vue的Vuex和React的Redux很雷同,都是Flow数据流。

对于React来说,state需要通过mapStateToProps将state传入到组件的props中,action需要通过mapDispatchToProps将action注入到组件的props中,然后在组件的props中获取并执行。

而在Vue中,store在组件的$store中,可以直接

this.$store.dispatch(actionType)
来分发action,属性也可以通过mapState,或者mapGetter把state或者getter挂载到组件的computed下,更粗暴的可以直接
this.$store.state
或者
this.$store.getter
获取,非常方便。

组件改造

我们为了更贴切于es6的class写法,更好的配合vue-class-component,我们需要通过其他的方式将store的数据注入到组件中。

vuex-class

vuex-class,这个包的出现,就是为了更好的讲Vuex与class方式的Vue组件连接起来。

如下,我们声明一个store


import Vuex from 'vuex';

const store = new Vuex.Store({
modules: {
foo: {
namespaced: true,
state: {
text: 'hello world',
},
actions: {
setTextAction: ({commit}, newText) => {