微信开发者工具实现监听效果

在vue项目之中有watch监听,在微信开发过程中也有需要监听的地方,防止多个页面调用时需要多次使用,将watch方法写在app.js之中

// 设置监听器
watch: function (ctx, obj) {
  Object.keys(obj).forEach(key => {
    this.observer(ctx.data, key, ctx.data[key], function (value) {
      obj[key].call(ctx, value)
    })
  })
},
// 监听属性,并执行监听函数
observer: function (data, key, val, fn) {
  Object.defineProperty(data, key, {
    configurable: true,
    enumerable: true,
    get: function () {
      return val
    },
    set: function (newVal) {
      if (newVal === val) return
      fn && fn(newVal)
      val = newVal
    },
  })
},

与 onLaunch() {}同级

在页面使用过程中,挂载到 onLoad()位置

      // 调用监听器,监听数据变化
      app.watch(this, {
        checkNum: function (newVal) {
          console.log(newVal,"监听到了")
        }
      })

是否开启深度监听同VUE一样

      app.watch(this, {
        checkNum: function (newVal) {
          console.log(newVal,"监听到了")
        },
        immediate: true
      })

猜你喜欢

转载自blog.csdn.net/weixin_51263829/article/details/128078378