this.setData , that.setData , this.data.val三者之间的区别和作用

1.this.setData({ })

    <view bindtouchmove="tap_drag" bindtouchend="tap_end" bindtouchstart="tap_start" class="page-top" style="{{translate}}">
View Code
      this.setData({
        translate: 'transform: translateX(' + this.data.windowWidth * 0.7 +'px);background-color: rgb(0, 68, 97);'
      })
View Code

上面的例子,通过this.setData改变了view的style属性,并且会同步改变视图

2.this.data.val

<view bindtouchmove="tap_drag" bindtouchend="tap_end" bindtouchstart="tap_start" class="page-top" style="{{translate}}">
this.data.translate = 'transform: translateX(0px)'
View Code

同样的数据绑定,通过 this.data.translate改变了data中的translate的值,此时数据变了,但是视图并不会变,这就导致了数据和视图不一致的问题 。可使用3中的示例1或者示例2酌情解决此问题。

3.that.setData({ })   这里看两个示例的不同结果进行对比

示例一: 示例一为错误示例 ,  会出现 this.setData is not a function 的报错,原因是此时的this对象指的是setTimeout  里面的匿名函数对象 , 但是在这种情况下还是想动态渲染视图,就需要把当前的this的状态保存起来,然后在 setTimeout  里面的匿名函数对象内调用。如示例二

  onLoad:function(){
    setTimeout(function () {
      this.setData({
        open: 111
      },1000)
    })
  },
View Code

示例二:保存当前对象的this状态,在 setTimeout  里面的匿名函数对象内调用 , 此时能够做到动态选择视图同时数据和视图都不会出错

  onLoad:function(){
    var that= this;
    setTimeout(function () {
      that.setData({
        open: 111
      },1000)
    })
  },

猜你喜欢

转载自www.cnblogs.com/niyl/p/10384367.html