您当前的位置: 首页 >  微信小程序

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

微信小程序:计算属性和监听属性miniprogram-computed

彭世瑜 发布时间:2021-10-20 14:16:08 ,浏览量:1

文档:

  • npm: https://www.npmjs.com/package/miniprogram-computed
  • github: https://github.com/wechat-miniprogram/computed

安装

npm install --save miniprogram-computed

注意:以下示例基于版本miniprogram-computed: ^4.0.4

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,
      });
    },
  },
});

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,
      });
    },
  },
});
关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.1295s