You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.2 KiB
55 lines
1.2 KiB
2 years ago
|
# Fix中对于对象属性的监听,为什么要先定义属性才可以正常watch,如何解决?
|
||
|
|
||
|
|
||
|
先看如下代码示例,很明显按钮被点击后并不会输出phone的值,其实这和Vue2类似,是因为Fix在响应式处理的时候,遍历对象的每一个属性添加依赖的,并不能检测到新增的属性.
|
||
|
|
||
|
```javascript
|
||
|
const state = Fix.define({
|
||
|
name: "小明",
|
||
|
details: {
|
||
|
age: 18,
|
||
|
address: "北京",
|
||
|
},
|
||
|
});
|
||
|
|
||
|
Fix.watch(state, "details.phone", phone => {
|
||
|
console.log(phone);
|
||
|
});
|
||
|
|
||
|
|
||
|
const widget = BI.createWidget({
|
||
|
type: "bi.button",
|
||
|
text: "button",
|
||
|
handler: () => {
|
||
|
state.details.phone = "123456789";
|
||
|
},
|
||
|
});
|
||
|
```
|
||
|
|
||
|
在日常实践中我们一般采用两种方式来处理这种情况
|
||
|
|
||
|
1. 修改整个对象的引用
|
||
|
|
||
|
```
|
||
|
const widget = BI.createWidget({
|
||
|
type: "bi.button",
|
||
|
text: "button",
|
||
|
handler: () => {
|
||
|
state.details = { ...state.details, phone: "123456789"};
|
||
|
},
|
||
|
});
|
||
|
```
|
||
|
|
||
|
2. 使用Fix.set方法
|
||
|
|
||
|
类似vue的$set方法
|
||
|
|
||
|
```
|
||
|
const widget = BI.createWidget({
|
||
|
type: "bi.button",
|
||
|
text: "button",
|
||
|
handler: () => {
|
||
|
Fix.set(state.details, "phone", "123456789");
|
||
|
},
|
||
|
});
|
||
|
```
|