+
95
-

回答

小程序不支持watch,不过可以通过两种办法解决:

一、自己写一个 watch功能

在app.js中增加以下代码

//设置监听器,page为页面
setWatcher(page) {
let data = page.data; // 获取page 页面data
let watch = page.watch;
for (let i in watch) {
let key = i.split('.'); // 将watch中的属性以'.'切分成数组
let nowData = data; // 将data赋值给nowData
let lastKey = key[key.length - 1];
let watchFun = watch[i].handler || watch[i]; // 兼容带handler和不带handler的两种写法
let deep = watch[i].deep; // 若未设置deep,则为undefine
this.observe(nowData, lastKey, watchFun, deep, page); // 监听nowData对象的lastKey
}
},
//监听属性 并执行监听函数
observe(obj, key, watchFun, deep, page) {
let val = obj[key];
// 判断deep是true 且 val不能为空 且 typeof val==='object'(数组内数值变化也需要深度监听)
if (deep && val != null && typeof val === 'object') {
for (let i in val) {
this.observe(val, i, watchFun, deep, page); // 递归调用监听函数
}
}
let that = this;
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function(value) {
// 用page对象调用,改变函数内this指向,以便this.data访问data内的属性值
watchFun.call(page, value, val); // value是新值,val是旧值
val = value;
if (deep) { // 若是深度监听,重新监听该对象,以便监听其属性。
that.observe(obj, key, watchFun, deep, page);
}
},
get: function() {
return val;
}
})
}

page页面使用:
onLoad: function() {
app.setWatcher(this);
setTimeout(() => {
this.setData({
name: "bfw"
})
}, 2000)
},
watch: {
name: {
handler(newValue, oldvalue) {
console.log(this)
console.log(newValue, oldvalue, "变化了");
},
deep: true
},
type: {
handler(newValue) {
console.log(newValue, "属性发生变化");
},
deep: true // 是否深度监听
}
},

二、引用第三方库

npm install --save miniprogram-computed

组件使用

const computedBehavior = require('miniprogram-computed')

Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
},
computed: {
sum(data) {
return data.a + data.b
},
},
})
const computedBehavior = require('miniprogram-computed')

Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
sum: 2,
},
watch: {
'a, b': function(a, b) {
this.setData({
sum: a + b
})
},
},
})

github地址https://github.com/wechat-miniprogram/computed

网友回复

我知道答案,我要回答