0

I like to use listenSwiper to capture swipe made in the swiper module, changing the previous and next items of the current item's style.

  listenSwiper: function(e) {
    var prev = 'items['+(e.detail.current-1)+'].x'
    var now = 'items['+(e.detail.current)+'].x'
    var next = 'items['+(e.detail.current+1)+'].x'
    console.log(prev)
    console.log(now)
    console.log(next)
    this.setData({
      prev:12,
      now:0,
      next:-12,
    })
  },

The problem is instead of recognizing prev, now, and next as variables, setData processed them as strings, which means it added three new keys in the existing array instead of modifying the array as such:

this.setData({
  'items[0].x':12,
  'items[1].x':0,
  'items[2].x':-12,
})
Aero Wang
  • 8,382
  • 14
  • 63
  • 99

1 Answers1

0

In ES5 or earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var data = {};
data[prev] = 12;
data[now] = 0;
data[next] = -12;

In ES6, you can use ComputedPropertyName. You can do it like this:

this.setData({
  [prev]: 12,
  [now]: 0,
  [next]: -12
})

similar question: Using a variable for a key in a JavaScript object literal

Link
  • 709
  • 7
  • 13