微信小程序获取多条列表,选择某一条点赞和取消赞的功能

是用wx:for得到列表;
点击这个列表中的某一项,是这个项目中的点赞数加1,再次点击减1,同时点赞的心形图标也相应变化。
从觉得获取不到点击的这一项的内容,不像angular那么的灵活。我用this获取也不能获取到。
有大神做过获取多条列表,单个点赞的吗?
阅读 7.3k
2 个回答

查询当前数据在数组中的索引,然后更改值就行了

// let id = xxx ,下面的查找条件
let currentIndex = this.data.list.findIndex(item => item.goods_id === id);
this.setData({
  ['list[' + currentIndex + '].added']: true
});

大概思路就这样,findIndex, 需要自己添加polyfill或者自定义一个方法

utils/array-findIndex.js 文件内容如下

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
if (!Array.prototype.findIndex) {
  Object.defineProperty(Array.prototype, 'findIndex', {
    value: function(predicate) {
      'use strict';
      if (this == null) {
        throw new TypeError('Array.prototype.findIndex called on null or undefined');
      }
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var list = Object(this);
      var length = list.length >>> 0;
      var thisArg = arguments[1];
      var value;

      for (var i = 0; i < length; i++) {
        value = list[i];
        if (predicate.call(thisArg, value, i, list)) {
          return i;
        }
      }
      return -1;
    },
    enumerable: false,
    configurable: false,
    writable: false
  });
}

app.js 中添加

// polyfill for Android before app starts
if (!Array.prototype.findIndex) {
  require('./utils/array-findIndex')
}

info.html

      <view class="common-list">
        <block wx:for="{{CommentData}}">
          <view class="list-item has-img" data-id="{{item.id}}">
            <view class="content">
              <view class="header">
                <view class='vbox'>
                  <text class="title">{{item.nickname}}</text>
                </view>
                <view class='vbox dianzan' bindtap='dianzan2' data-id="{{item.id}}">
                  <image class="vote" src="../../images/{{item.active ? 'thumb_up_active.png':'thumb_up.png'}}" />{{item.dianzan}}
                </view>
              </view>
              <text class="body">{{item.content}}</text>
              <text class="bottom">{{item.time_str}}</text>

            </view>
            <image src="{{item.head_pic}}" class="cover" />
          </view>
        </block>
      </view>

info.js

  dianzan2:function(e){
    let comid=e.currentTarget.dataset.id;
    let tmp = this.data.CommentData.map(function (arr, index) {    
      if (comid == arr.id) {       
        if (arr.active){
          arr.active = false;
          arr.dianzan--;
        }else{
          arr.active = true;
          arr.dianzan++;
        }
        //发送请求保存结果到数据库
      }
      return arr;
    })
    this.setData({ CommentData: tmp });  
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进