Vue与React都鼓励组件化应用,即将应用分拆成一个个功能明确的模块,每个模块之间可以通过合适的方式互相联系,但各自的实现略有不同。以下谈谈我的理解,如有不对,欢迎指正
在Vue组件中,有几个观念和React相差比较大,我觉得主要有以下这几点:
-
Vue组件分为全局注册和局部注册,在react中都是通过import相应组件,然后模版中引用
-
props是可以动态变化的,子组件也实时更新,在react中官方建议props要像纯函数那样,输入输出一致对应,而且不太建议通过props来更改视图
-
子组件一般要显示地调用props选项来声明它期待获得的数据。而在react中不必需,另两者都有props校验机制
-
每个Vue实例都实现了事件接口,方便父子组件通信,小型项目中不需要引入状态管理机制,而react必需自己实现
-
使用插槽分发内容,使得可以混合父组件的内容与子组件自己的模板
-
多了指令系统,让模版可以实现更丰富的功能,而React只能使用JSX语法
-
Vue增加的语法糖computed和watch,而在React中需要自己写一套逻辑来实现
0x01 组件的注册
1.Vue
Vue组件注册可分为全局注册和局部注册
-
全局注册
需在初始化根实例之前注册组件
//html
<div id="example">
<my-component></my-component>
</div>
// 注册
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 创建根实例
new Vue({
el: '#example'
})
- 局部注册
通过Vue 实例/组件的实例选项 components 注册仅在其作用域中可用的组件。这种封装也适用于其它可注册的 Vue 功能,比如指令。
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
// ...
components: {
// <my-component> 将只在父组件模板中可用
'my-component': Child
}
})
2. React
React组件没有全局注册和局部注册的概念,官方推荐以ES6的class来创建组件,调用通过import导入组件实例
import React from "react";
class Demo extends React.Component {
constructor(props) {
super(props);
// 设置 initial state
this.state = {
text: props.initialValue || 'placeholder'
};
// ES6 类中函数必须手动绑定,也可在调用的时候绑定,或者通过箭头函数
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
text: event.target.value
});
}
render() {
return (
<div>
Type something:
<input onChange={this.handleChange}
value={this.state.text} />
</div>
);
}
}
export default Demo;