behavior.js
1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function setAsync(context, data) {
return new Promise(resolve => {
context.setData(data, resolve);
});
}
;
export const behavior = Behavior({
created() {
if (!this.$options) {
return;
}
const cache = {};
const { computed } = this.$options();
const keys = Object.keys(computed);
this.calcComputed = () => {
const needUpdate = {};
keys.forEach(key => {
const value = computed[key].call(this);
if (cache[key] !== value) {
cache[key] = needUpdate[key] = value;
}
});
return needUpdate;
};
},
attached() {
this.set();
},
methods: {
// set data and set computed data
set(data, callback) {
const stack = [];
if (data) {
stack.push(setAsync(this, data));
}
if (this.calcComputed) {
stack.push(setAsync(this, this.calcComputed()));
}
return Promise.all(stack).then(res => {
if (callback && typeof callback === 'function') {
callback.call(this);
}
return res;
});
}
}
});