收藏
回答

关于this.setData无效的问题?

我写了1个最简单的测试代码都无效。

1、test.js代码如下:
Page({
    data: { selected: [] },
    tapA() {
      this.setData({ selected: this.data.selected.includes('a') ? [] : ['a'] });
    },
    tapB() {
      this.setData({ selected: this.data.selected.includes('b') ? [] : ['b'] });
    }
  });
2、test.wxml代码如下:
<view class="container">
  <!-- A 按钮 -->
  <view 
    class="item {{selected.includes('a') ? 'selected' : ''}}" 
    bindtap="tapA"
  > A
  </view>
  <!-- B 按钮 -->
  <view 
    class="item {{selected.includes('b') ? 'selected' : ''}}" 
    bindtap="tapB"
  > B
  </view>
  <text>当前选中: {{selected}}</text>
</view>
3、test.wxss代码如下:
/* 容器样式 */
.container {
  padding: 20rpx;
}


/* 默认按钮样式 */
.item {
  padding: 30rpx;
  margin: 20rpx 0;
  background: #eee;
  color: #333;
  text-align: center;
}


/* 选中时的按钮样式 */
.item.selected {
  background: #ff0000;
  color: #fff;
  font-size: 40rpx !important;    /* 字体放大 */
  border: 5px solid #000 !important; /* 黑色边框 */
}

为什么当选择A或者B不会触发selected效果??
回答关注问题邀请回答
收藏

1 个回答

  • 金瓜兜儿
    金瓜兜儿
    发表于小程序端
    06-12

    wxml中好像不支持数组、对象的一些方法,改为字符串判断,或者setData直接设置变量来控制吧

    06-12
    有用
    回复 1
    • 狐狸的主子
      狐狸的主子
      发表于小程序端
      06-12

      好的,谢谢

      06-12
      回复
登录 后发表内容