Monitor the data changes of the WeChat applet page

1. Data monitoring is to do some operations when the data changes;

2. It is equivalent to the watch listener in Vue

First look at the effect:

First, use it on the page first 

        ①: Create a watch file

export function setWatcher(page) {
  let data = page.data;
  let watch = page.watch;
  Object.keys(watch).forEach(v => {
      let key = v.split('.');
      let nowData = data;
      for (let i = 0; i < key.length - 1; i++) {
          nowData = nowData[key[i]];
      }
      let lastKey = key[key.length - 1];
      let watchFun = watch[v].handler || watch[v];
      let deep = watch[v].deep;
      observe(nowData, lastKey, watchFun, deep, page);
  })
}

function observe(obj, key, watchFun, deep, page) {
  var val = obj[key];
  if (deep && val != null && typeof val === 'object') {
      Object.keys(val).forEach(childKey => {
          observe(val, childKey, watchFun, deep, page);
      })
  }
  Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function(newVal) {
          watchFun.call(page, newVal, val); 
          val = newVal;
          if (deep) {
              observe(obj, key, watchFun, deep, page);
          }
      },
      get: function() {
          return val;
      }
  })
}
module.exports = {
  setWatcher: setWatcher
}

        ②: Introduce and use in the page

        wxml:

<input bindinput="inputFrame" model:value="{
    
    {count}}" type="text" placeholder="监听数据的变化"/>

        js:

import { setWatcher } from '../../utils/watch';
Page({
  data: {
    count:''
  },
  inputFrame(){
    setWatcher(this);
    // console.log('正在输入',this.data.count)
  },
  watch: {
    val(v) {
      console.log(v)
    },
    count: {
      handler(v,o) {
        console.log('新值:'+v,'旧值:'+o)
        if(v!==o){
          console.log('被改了')
        }else{
          console.log('没改')
        }
      },
      deep: true
    }
  },
  
})

Second: use data monitoring in components 

        ①:wxml:

        

<view>{
    
    {n1}} + {
    
    {n2}} = {
    
    {sum}}</view>

<button bindtap="addN1">n1+1</button>

<button bindtap="addN2">n2+1</button>

        ②:JS:

        

Component({

  /**

   * 组件的初始数据

   */

  data: {

    n1: 0,

    n2: 0,

    sum: 0

  },

  /**

   * 组件的方法列表

   */

  methods: {

    addN1() {

      this.setData({

        n1: this.data.n1 + 1

      })

    },

    addN2() {

      this.setData({

        n2: this.data.n2 + 1

      })

    }

  },

  observers: { // 数据监听数据

    'n1, n2': function (newN1, newN2) { // 监听 n1 和 n2 的数据变化

      this.setData({

        sum: newN1 + newN2 // 通过监听器,自动计算 sum 的值

      })

    }

  }

})

        

Guess you like

Origin blog.csdn.net/qq_17211063/article/details/130603186