Bootstrap

微信小程序实现类似Vue中的computed、watch功能

微信小程序实现类似Vue中的computed、watch功能

构建npm

  1. 创建包管理器
    进入小程序后,打开终端,点击顶部“视图” - “终端”
    在这里插入图片描述
    新建终端
    在这里插入图片描述
    使用 npm init -y初始化包管理器,生成一个package.json文件
    在这里插入图片描述

  2. 安装 npm 包

    npm install --save miniprogram-computed
    
  3. 构建npm
    点击开发者工具中的菜单栏:工具 --> 构建 npm
    在这里插入图片描述

使用

在自定义组件中,以require的方式引入

  1. computed 基本用法
    const computedBehavior = require('miniprogram-computed').behavior
    Component({
      behaviors: [computedBehavior],
      data: {
        a: 1,
        b: 1,
      },
      computed: {
        sum(data) {
          // 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
          // 这个函数的返回值会被设置到 this.data.sum 字段中
          return data.a + data.b
        },
      },
      methods: {
        onTap() {
          this.setData({
            a: this.data.b,
            b: this.data.a + this.data.b,
          })
        },
      },
    })
    
  2. watch 基本用法
    const computedBehavior = require('miniprogram-computed').behavior
    
    Component({
      behaviors: [computedBehavior],
      data: {
        a: 1,
        b: 1,
        sum: 2,
      },
      watch: {
        'a, b': function (a, b) {
          this.setData({
            sum: a + b,
          })
        },
      },
      methods: {
        onTap() {
          this.setData({
            a: this.data.b,
            b: this.data.a + this.data.b,
          })
        },
      },
    })
    
;