微信小程序在做图片预览时,发现点击图片预览,onShow中的所有接口都重新调用了一遍,整个界面都刷新了,还会引发一系列的问题。

<image src="{{url}}" style="height: 300rpx;width: 300rpx" bindtap="goPreview"></image>
goPreview() {
  wx.previewImage({
    current: this.data.url, 
    urls: [this.data.url]
  })
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
  console.log('触发了onShow函数');
},

/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
  console.log('触发了onHide函数');
}

通过操作可以发现,点击图片预览时会触发onShow函数,再次点击图片取消预览时会触发onHide函数。
在onShow函数里写了调用了后端的接口,界面就会刷新
解决方法如下:

一、设置变量isPreview

在data中设置变量isPreview,默认值为false会触发onShow函数,当值为true时不触发onShow函数。

二、点击图片预览时设置isPreview的值

触发goPreview方法时设置isPreview的值为true

goPreview() {
  this.setData({isPreview: true})
  wx.previewImage({
    current: this.data.url, 
    urls: [this.data.url]
  })
}
三、在onShow函数中添加判断

点击图片,isPreview为true,则不触发onShow函数,重新把isPreview的值设置为false;

onShow: function () {
  if(this.data.isPreview) {
    this.setData({isPreview:false})
  } else {
    // doFunction() 调用接口
  }
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐