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

推荐订阅源

V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
博客园 - 【当耐特】
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
美团技术团队
WordPress大学
WordPress大学
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
IT之家
IT之家
T
Tailwind CSS Blog
月光博客
月光博客
Vercel News
Vercel News
V
V2EX
Engineering at Meta
Engineering at Meta
B
Blog
Stack Overflow Blog
Stack Overflow Blog
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
腾讯CDC
I
InfoQ

时间的朋友

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) {
            ...
        }
    }
})