40行代码把行代码把Vue3的响应式集成进的响应式集成进React做状态管理做状态管理
主要介绍了40行代码把Vue3的响应式集成进React做状态管理,文中通过示例代码介绍的非常详细,对大家的学习或者
工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
前言前言
vue-next是Vue3的源码仓库,Vue3采用lerna做package的划分,而响应式能力@vue/reactivity被划分到了单独的一个package中。
如果我们想把它集成到React中,可行吗?来试一试吧。
使用示例使用示例
话不多说,先看看怎么用的解解馋吧。
// store.ts
import { reactive, computed, effect } from '@vue/reactivity';
export const state = reactive({
count: 0,
});
const plusOne = computed(() => state.count + 1);
effect(() => {
console.log('plusOne changed: ', plusOne);
});
const add = () => (state.count += 1);
export const mutations = {
// mutation
add,
};
export const store = {
state,
computed: {
plusOne,
},
};
export type Store = typeof store;
// Index.tsx
import { Provider, useStore } from 'rxv'
import { mutations, store, Store } from './store.ts'
function Count() {
const countState = useStore((store: Store) => {
const { state, computed } = store;
const { count } = state;
const { plusOne } = computed;
return {
count,
plusOne,
};
});
return (
<Card hoverable style={{ marginBottom: 24 }}>
<h1>计数器</h1>
<div className="chunk">
<div className="chunk">store中的count现在是 {countState.count}</div>
<div className="chunk">computed值中的plusOne现在是 {countState.plusOne.value}</div>
<Button onClick={mutations.add}>add</Button>
</div>
</Card>
);
}
export default () => {
return (
<Provider value={store}>
<Count />
</Provider>
);
};
可以看出,store的定义只用到了@vue/reactivity,而rxv只是在组件中做了一层桥接,连通了Vue3和React,然后我们就可以尽情的
使用Vue3的响应式能力啦。