微信小程序 computed 实现

本文介绍了微信小程序 computed 的实现方法,包括将 computed 作为 behavior 引入,把 Page({}) 修改为 Component({}),将基础版本库改到 2.61 以上。同时指出 computed 属性只能计算一层,引用其他计算属性会导致计算值紊乱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信小程序 computed 实现

  1. 安装 computed: computed
npm install --save miniprogram-computed
  1. 作为 behavior 引入
const computedBehavior = require('miniprogram-computed')

Component({
  behaviors: [computedBehavior],
  data: {
    a: 0,
  },
  computed: {
    b() {
      // 计算属性同样挂在 data 上,每当进行 setData 的时候会重新计算
      // 比如此字段可以通过 this.data.b 获取到
      return this.data.a + 100
    },
  },
  methods: {
    onTap() {
      this.setData({
        a: ++this.data.a,
      })
    }
  }
})
<view>data: {{a}}</view>
<view>computed: {{b}}</view>
<button bindtap="onTap">click</button>
  1. 把 Page({}) 修改为 Component({})
  2. 把基础版本库改到2.61 以上,详情-> 本地设置 -> 基础版本库
  3. 然后就可以愉快的使用computed属性了,使用方法和组件Component 组件用法一致
  4. computed 属性只能计算一层,当引用另一个计算属性时,会首先计算这个在计算引用的计算属性,导致计算值紊乱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值