Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

本人使用的是旧版weex语法开发的H5网站

在使用storage组件中发现getItem回调函数中的值,只能在该方法中使用,即使绑定在data中,其他的function也不能通过this.xxx的方法取得值

data:{
    productId:0;    //这里定义一个productId
}


method:{
    //获得productId
    getId:function(){
        var self = this;
        storage.getItem('productId',function(res){      //从浏览器取得productId
        self.productId = res.data;
      })
    }
    //使用productId
    useId:function(){
        var productId = self.productId;
        console.log(productId);    //我试过,在这里是取不到data中的productId的,打印结果为undefined
    }
}

当然会有人说,为什么不在getItem的回调里面使用传参的方式,这种方式我知道

 //获得productId
 getId:function(){
        var self = this;
        storage.getItem('productId',function(res){      //从浏览器取得productId
            self.productId = res.data;
            self.useId(res.data)   *在这里对userId方法传入参数*
        })
    }
 //使用productId
    useId:function(value){        *在这里接收参数*
        var self = this;
        var productId = self.productId;
        console.log(productId);    
    }

提的问题,是我在开发中遇到的一种情况,有的时候一个onclick里面不想带上其他的function,有其他人遇到这个问题吗? 还是我的写法有问题,或者文档有说明我没看到- -(至少storage这块我没看到)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

我自己现在用这个方法,如果大家有更好的方法,可以教教我 谢谢啦!

1---在data中先定义要绑定的参数

data{
    newValue:0
}

2---在method中自定义一个接受参数并绑定参数的方法

method:{
    getValue:function(value){
        this.newValue= value
    }
}

3---在storage.getItem的回调中,将参数传入自定义方法

storage.getItem('xxx',function(res){
 //我习惯在这里重新定义self了,因为之前有被这个坑过,在有些地方需要重新定义this指向,不然也获取不到值
    var self = this;       
    var value = res.data;
    self.getValue(value);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...