先上代碼----// pages/three/three.jsPage({ /** * 頁面的初始數(shù)據(jù) */ data: { name:"", age:"", sex:"" }, onLoad: function (options) { this.setWatch(this); console.log(this) }, watch:{ name(){ console.log('我是name') console.log(111111) }, age(){ console.log(this.data.name) console.log('我是age') }, sex(){ console.log('sex') } }, onReady: function () { }, btn(){ this.setData({ name:1 }) }, setWatch(){ let watch=this.watch; let _this=this; // Object.keys(watch).forEach(v=>{ // console.log(v) // var setVal = _this.data[v]; // Object.defineProperty(_this.data,v,{ // configurable: true, // enumerable: true, // get:function(){ // return setVal // }, // set:function(val){ // setVal=val; // _this.watch[v].call(_this); // } // }) // }) for(var v in watch){ console.log(v) var setVal=_this.data[v]; Object.defineProperty(_this.data,v,{ configurable: true, enumerable: true, get:function(){ return setVal }, set:function(val){ setVal=val; console.log(_this.watch[v]) _this.watch[v].call(_this); } }) } }})我用for(var i in obj){}來給對象添加get和set方法的時候,監(jiān)聽的事件永遠只是watch對象里的最后一個方法,就是說,不管我修改name還是age的值,執(zhí)行的都是watch里的sex方法,但是我用Object.keys(obj)來添加的時候,執(zhí)行的事件卻是正常的,求大佬解決
關(guān)于自己封裝類似vue中watch監(jiān)聽事件的一個問題
四季花海
2019-03-21 22:15:18