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.
|
|
|
# watch使用的常见误区
|
|
|
|
|
|
|
|
|
|
|
|
## watch职责不单一,掺杂额外处理逻辑
|
|
|
|
|
|
|
|
最常见的场景为在watch中掺杂调用loading和loaded方法.这样做的弊端在于loading状态的控制没有形成明显闭环,有可能出现loading触发了,但是没有后续的loaded,导致用于在加载中
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
watch: {
|
|
|
|
items: function (items) {
|
|
|
|
this.loading();
|
|
|
|
// do someting
|
|
|
|
},
|
|
|
|
},
|
|
|
|
```
|
|
|
|
比较合理的做法是在触发异步获取数据的action中进行loading状态的切换,即异步请求发起前状态切换到loading,请求结束后切换到loaded
|
|
|
|
```javascript
|
|
|
|
// model.js
|
|
|
|
actions: {
|
|
|
|
getItems: function (items) {
|
|
|
|
this.model.loading = true;
|
|
|
|
requestItems().then(() => {
|
|
|
|
// do something
|
|
|
|
this.model.loaded = false;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
},
|
|
|
|
|
|
|
|
// widget.js
|
|
|
|
watch: {
|
|
|
|
loading: function (b) {
|
|
|
|
b : this.loading() : this.loaded();
|
|
|
|
},
|
|
|
|
},
|
|
|
|
```
|
|
|
|
|
|
|
|
## 在组件的watch中回过头来调用store中的action
|
|
|
|
|
|
|
|
类似于经济上的出口转内销,在watch中调用action修改状态,进而触发另外的watch.
|
|
|
|
这样是不优雅的,实际业务中确实存在watch某个状态改变触发action的场景,例如通过watch上层的keyword状态,触发搜索action.
|
|
|
|
很多同学忽视了其实store中也可以进行watch的,合理的实现是将状态改变全都放在store里,在store中进行watch
|
|
|
|
|
|
|
|
不佳的实现
|
|
|
|
```javascript
|
|
|
|
// model.js
|
|
|
|
context: ["keyword"],
|
|
|
|
|
|
|
|
state: function () {
|
|
|
|
return {
|
|
|
|
b: 22,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
|
|
|
actions: {
|
|
|
|
changeB: function () {
|
|
|
|
this.model.b++;
|
|
|
|
},
|
|
|
|
},
|
|
|
|
|
|
|
|
// widget.js
|
|
|
|
watch: {
|
|
|
|
keyword: function () {
|
|
|
|
this.store.changeB();
|
|
|
|
},
|
|
|
|
},
|
|
|
|
```
|
|
|
|
更为合理的实现
|
|
|
|
```javascript
|
|
|
|
// model.js
|
|
|
|
context: ["keyword"],
|
|
|
|
|
|
|
|
state: function () {
|
|
|
|
return {
|
|
|
|
b: 22,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
|
|
|
watch: {
|
|
|
|
keyword: function () {
|
|
|
|
this.store.changeB();
|
|
|
|
},
|
|
|
|
},
|
|
|
|
|
|
|
|
actions: {
|
|
|
|
changeB: function () {
|
|
|
|
this.model.b++;
|
|
|
|
},
|
|
|
|
},
|
|
|
|
```
|
|
|
|
|
|
|
|
业务代码示例
|
|
|
|
![示例](../images/45.png)
|