使用proxy替代setData实现小程序 数据代理

小程序 数据代理

微信开发工具导入项目

  新建项目 -> 导入src文件 -> 预览效果

代码

proxy.js

  const nativePage = Page
  const nativeComponent = Component
  Page = (options, key = 'onLoad') => {
    const native = options[key]
    options[key] = function () {
      this.ctx = proxy.call(this)
      return native && native.call(this)
    }
    key === 'onLoad' ? nativePage(options) : nativeComponent(options)
  }
  Component = options => Page(options, 'created')

  function proxy() {
    let pending = false
    const setData = () => {
      pending = true
      setTimeout(() => {
        this.setData(this.data, () => pending = false)
      })
    }

    const handler = {
      get(target, key, receiver) {
        try {
          if (typeof target[key] === 'function') return Reflect.get(target, key, receiver)
          return new Proxy(target[key], handler)
        } catch (err) {
          return Reflect.get(target, key, receiver)
        }
      },
      set(target, key, value, receiver) {
        if (!(Array.isArray(target) && key !== 'length')) !pending && setData()
        return Reflect.set(target, key, value, receiver)
      },
      deleteProperty(target, key) {
        !pending && setData()
        return Reflect.deleteProperty(target, key)
      }
    }
    return new Proxy(this.data, handler)
  }
### 使用 > 在 app.js 中引入 proxy.js 文件
  require('./vendor/proxy.js')

在 index 页面中的 index.js 中使用

  onLoad: function () {
    this.ctx.motto = 'Hello Echo'
    this.ctx.user.name = 'Echo'
  }

在 movable 组件中的 movable.js 中使用

  created: function () {
    this.ctx.visible = true
  }
截图预览 > 数据更新前 和 更新后 对比

原理说明

  • 拦截数据变化,调用 this.setData 方法
  • 多条数据变化,合并一次更新
  • 代理对象绑定到 this.ctx 上下文中,同步更新 this.data 数据

链接地址

github: 使用proxy替代setData实现小程序 数据代理

小程序: 使用proxy替代setData实现小程序 数据代理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值