设计思想
vue用的是渐进式,先从核心功能开始,然后逐渐扩展。vue2使用Object.defineProperty() ,vue3改用了proxy进行双向数据绑定。
React 则主张函数式编程,组件式开发,单向数据流。如果我们需要双向数据流可以通过onChange方法,setState 方法
编写方法
vue使用的是模板写法,保留了html,js,css分离。
react使用的是jsx语法,即:html,css,js都写在了js里面。
组件的通信
vue的通信方式:
1)、父组件通过props向子组件传递数据,子组件通过$emit发送事件向父组件传递数据;
2)、兄弟组件通过父组件查找子组件实现,也就是this.$parent.$children ,在 $children 中通过组件 name 查询到需要的组件实例,然后进行通信;
3)、使用provide / inject进行跨多层次组件通信。
react通信方式:
1)、父组件通过 props 传递数据给子组件,子组件通过调用父组件传来的函数传递数据给父组件;
2)、兄弟组件可以通过共同的父组件来管理状态和事件函数,比如说其中一个兄弟组件调用父组件传递过来的事件函数修改父组件中的状态,然后父组件将状态传递给另一个兄弟组件;
3)、通过 context (16.3 以上版本)进行跨层级的通信,这和 provide/inject 起到的作用差不多。
// 创建 Context,可以在开始就传入值
const StateContext = React.createContext()
class Parent extends React.Component {
render () {
return (
// value 就是传入 Context 中的值
<StateContext.Provider value='yck'>
<Child />
</StateContext.Provider>
)
}
}
class Child extends React.Component {
render () {
return (
<ThemeContext.Consumer>
// 取出值
{context => (
name is { context }
)}
</ThemeContext.Consumer>
);
}
}vuex和redux
Vuex 的$store 被直接注入到了组件实例,使用dispatch 和 commit 提交更新,然后通过 mapState 或者直接通过 this.$store 来读取数据。
redux每一个组件都需要显示的用 connect 把需要的 props 和 dispatch 连接起来。