惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
C
Check Point Blog
I
InfoQ
A
About on SuperTechFans
Engineering at Meta
Engineering at Meta
月光博客
月光博客
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
Y
Y Combinator Blog
博客园 - Franky
博客园_首页
罗磊的独立博客
量子位
美团技术团队
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Martin Fowler
Martin Fowler
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
小程序中监听data中数据变化方式 | 时间的朋友
2021-10-08 · via 时间的朋友

Published: · LastMod: March 30, 2023 · 523 words

小程序中监听data中数据变量的变化 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 监听页面数据变化
export const PageWatch = (_page) => {
  if (!_page) {
    console.error('未检测到Page对象,请将当前page传入该函数');
    return false;
  }
  if (!_page.watch) { //判断是否有需要监听的字段
    console.error('未检测到Page.watch字段(如果不需要监听,请移除initWatch的调用片段)');
    return false;
  }
  let _dataKey = Object.keys(_page.data);
  Object.keys(_page.watch).map((_key) => { //遍历需要监听的字段
    _page.data['__' + _key] = _page.data[_key]; //存储监听的数据
    if (_dataKey.includes(_key)) { //如果该字段存在于Page.data中,说明合法
      Object.defineProperties(_page.data, {
        [_key]: { //被监听的字段
          enumerable: true,
          configurable: true,
          set: function (value) {
            let oldVal = this['__' + _key];
            if (value !== oldVal) { //如果新设置的值与原值不等,则触发监听函数
              setTimeout(function () { //为了同步,否则如果回调函数中有获取该字段值数据时将不同步,获取到的是旧值
                _page.watch[_key].call(_page, oldVal, value); //设置监听函数的上下文对象为当前的Page对象并执行
              }.bind(this), 0);
            }
            this['__' + _key] = value;
          },
          get: function () {
            return this['__' + _key];
          }
        }
      });
    } else {
      console.error('监听的属性[' + _key + ']在Page.data中未找到,请检查~');
    }
  });
};

使用方法 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Page({
    data: {
        foo: 'abc'
    },
    watch: {
        'foo': function(newValue, oldValue) {
            ...
        }
    }
})