【微信小程序】用Proxy实现双向绑定(类Vuex)

自己写的,如有问题欢迎指教

[核心代码]根目录/store.js

// 根目录/store.js
let app = getApp()

const Store = function (obj, useStates = {}) {
  return new Proxy(app.globalData, {
    set(target, key, value) {
      if (Array.isArray(useStates) && useStates.includes(key)) {
        obj.setData({
          [key]: value
        })
      } else if (useStates instanceof Object && useStates.hasOwnProperty(key)) {
        obj.setData({
          [key]: value
        })
      }
      return Reflect.set(target, key, value)
    },
    get(target, key) {
      return Reflect.get(target, key)
    }
  })
}

export const bindStore = function (obj, useStates = {}) {
  let tmpData = {}
  if (Array.isArray(useStates)) {
    for(let i in useStates) {
      tmpData[useStates[i]] = app.globalData[useStates[i]]
    }
    obj.setData(tmpData)
  } else if (useStates instanceof Object) {
    for (let i in useStates) {
      tmpData[i] = app.globalData[useStates[i]]
    }
    obj.setData(tmpData)
  }
  return Store(obj, useStates)
}

【使用说明】

// 直接import bindStore函数
bindStore(
  this, //本页对象	
  ['userInfo'], //使用的state,可为对象,{userInfo1/*本页绑定的名称*/: 'userInfo'/*指向名称*/}
  ['setUserInfo'] //使用的mutation,未添加,有空加,打算把核心代码抽取出来搞
)

【测试代码】根目录下/pages/index/index.wxml

<text>pages/login/index.wxmltext>
<view>{{userInfo.a}}view>
<navigator url="/pages/logs/logs">走起navigator>

【测试代码】根目录下/pages/logs/logs.wxml

<text>pages/logs/logs.wxmltext>
<view>{{userInfo.a}}view>

【测试代码】根目录下/pages/logs/logs.js

// pages/logs/index.js
const util = require('../../utils/util.js')
import { bindStore} from '../../store.js'
Page({
  onLoad: function () {
    let store = bindStore(this,{
      userInfo: 'userInfo'
    })
  }
})

【测试代码】根目录下/pages/login/index.js

// pages/login/index.js
import { bindStore} from '../../store.js'
Page({
  onLoad: function (options) {
    let store = bindStore(this, ['userInfo'])
    let r = ''
    setInterval(() => {
      r += '1'
      store.userInfo = { a: r }
    },1000)
  }
})

你可能感兴趣的:(前端)