小程序的 MobX在 store 中的字段被更新后,怎么立刻同步更新到 this.data 上
时间: 2024-02-03 07:11:17 浏览: 26
要实现 MobX store 中的字段更新后立刻同步更新到小程序中,可以使用 `@observer` 装饰器来监听 store 中的变化,并使用 `this.setData()` 方法将变化同步到 `this.data` 中。
具体操作步骤如下:
1. 在小程序的页面中引入 `mobx-miniprogram-bindings` 库
```javascript
import { observer } from 'mobx-miniprogram-bindings';
```
2. 在页面的 `onLoad` 函数中使用 `observer` 装饰器绑定 store 和页面
```javascript
import { observer } from 'mobx-miniprogram-bindings';
import { store } from '../../store';
Page(
observer({
onLoad() {
//...
},
})
);
```
3. 在页面的 `data` 中添加需要同步的字段
```javascript
Page(
observer({
data: {
name: '',
age: 0,
},
onLoad() {
//...
},
})
);
```
4. 在 store 中使用 `observable` 包装需要同步的字段,并在页面中使用 `computed` 获取这些字段的值
```javascript
import { observable, computed } from 'mobx-miniprogram';
export const store = observable({
name: '小明',
age: 18,
});
export const computedStore = computed(() => ({
name: store.name,
age: store.age,
}));
```
5. 在页面中使用 `computedStore` 来获取被观察的字段,并在 `onLoad` 函数中监听这些字段的变化并同步到 `this.data` 中
```javascript
Page(
observer({
data: {
name: '',
age: 0,
},
onLoad() {
this.setData({
name: computedStore.name,
age: computedStore.age,
});
// 监听 store 中的值的变化并同步到 this.data 中
this.disposer = computedStore.observe(() => {
this.setData({
name: computedStore.name,
age: computedStore.age,
});
});
},
onUnload() {
this.disposer();
},
})
);
```
以上就是使用 MobX 在 store 中的字段被更新后立刻同步更新到 this.data 上的步骤。