微信小程序setData内如何使用变量做指针?

我要用listenSwiper听取swiper的变化,改变被选中的swiper-item之前和之后的swiper-item的样式。我用的代码如下:

  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,
    })
  },

这是不会成功是因为微信小程序自动把prev、now、next这三个变量当作了string来处理。也就是所并不是修改了:

this.setData({
  'items[0].x':12,
  'items[1].x':0,
  'items[2].x':-12,
})

而是添加了:

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

有没有什么好办法来解决这个问题/挑战?

另外我刚刚发现了……微信小程序根本不允许变量啊。

阅读 4.6k
2 个回答
 listenSwiper: function(e) {
    let updataData = {};
    updateData['items['+(e.detail.current-1)+'].x'] = 12;
    updateData['items['+(e.detail.current-1)+'].x'] = 0;
    updateData['items['+(e.detail.current-1)+'].x'] = -12;
    this.setData(updataData);
  },
新手上路,请多包涵

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'
this.setData({
  [prev]:12,
  [now]:0,
  [next]:-12,
})

},

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题