目录

微信小程序小程序中计算属性的使用

目录

微信小程序——小程序中计算属性的使用

https://img-home.csdnimg.cn/images/20240715101418.png

关键词由CSDN通过智能技术生成

1、下载npm包

npm install --save miniprogram-computed

2、微信开发者工具——工具 ——构建npm ——构建完成点击确定

demo.js

const computedBehavior = require("miniprogram-computed").behavior;

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

demo.wxml

<view>A = {{a}}</view>
<view>B = {{b}}</view>
<view>SUM = {{sum}}</view>
<button bindtap="onTap">click</button>

更多案例请看