vscode+gulp 舒舒服服开发小程序(2)

171 阅读1分钟

继上一篇开发内容,本次文章是针对小程序实现computedwatch 方法

原文链接: vscode+gulp 舒舒服服开发小程序

新增watch 和 computed

如在小程序 index页面中

Page({
  onLoad() {
      // somecode
  }
  watch: {
    handleWatch() {
        return this.data.xxx
    }
  }
  computed: {
    computedHandle() {
        return this.data.xxx
    }
  }
})

本身想基于wx去扩展page方法的,但是page类实体,在为初始化下,不存在onload方法,也不能用setData等方式进行操作,所以基于Pageonload方法进行扩展

  • 利用vue2.x版本的响应式原理,基于defineProperty方法,进行扩展,最主要的也是setget操作 相对应的代码实现位于:
// /toulPlugins/extendPage.js页面
// 扩展与onLoad方法
function computed(ctx, obj) {...somecode} 
function defineReactive(data, key, val, fn) {
  let subs = data['$' + key] || [] 
  Object.defineProperty(data, key, {
    configurable: true,
    enumerable: true,
    get: function () {
      if (data.$target) { // 
        subs.push(data.$target)
        data['$' + key] = subs
      }
      return val
    },
    set: function (newVal) {
      if (newVal === val) return
      fn && fn(val, newVal)

      if (subs.length) {
        // 用 setTimeout 因为此时 this.data 还没更新
        setTimeout(() => {
          subs.forEach(sub => sub())
        }, 0)
      }
      val = newVal
    },
  })
}

修复

在前篇文章中,针对config配置,alisa修改成了alias 具体详情可以看git提交记录

具体详细文档: wechat-mini-program-gulp