一、报错
出现this.setData is not a function
报错的绝大多数情况是,在回调时,this指向作用域为当前异步方法所在的对象,详见微信小程序异常处理——this.setData is not a function报错处理
二、排查原因
但我并没有在回调中使用this.setData()
,仅在onLoad里使用也报了这个错误,于是将问题定位到使用了uni-app框架的原因上。
三、解决方式:
3.1 直接使用this.xx = xxx
修改:
this.setData({loading: false,areaList: response.data.data
})
为:
this.loading = false;
this.areaList = response.data.data。
3.2 重写setData方法
setData:function(obj){
let that = this;
let keys = [];
let val,data;
Object.keys(obj).forEach(function(key){ keys = key.split('.'); val = obj[key]; data = that.$data; keys.forEach(function(key2,index){ if(index+1 == keys.length){ that.$set(data,key2,val); }else{ if(!data[key2]){ that.$set(data,key2,{}); } } data = data[key2]; })
});
}
四、实例 setData+scroll-into-view实现页面加载时分页组件滚到最底部
- scroll-view要给定高度
- 在uni-app中不要使用
{{}}
来绑定动态属性
<template><view style="padding:50rpx 10rpx;border:1px solid #333"><scroll-view style="border:1px solid #000;height:500rpx;" scroll-y :scroll-into-view="toLast"><viewv-for="(item,index) in testList":key="item.id"style="border:1px solid #ccc;":id="'item'+index"><view class="a" style="margin:20rpx 0">{{item.a}}</view><view class="q" style="margin:20rpx 0">{{item.q}}</view></view></scroll-view></view>
</template><script>
export default {onLoad() {this.toLast = "item8";this.setData({ toLast: "item8" });},data() {return {test1: "01",test2: "02",toLast: "item",testList: [{ id: 1, q: "1qwert", a: "1asdfg" },{ id: 2, q: "2qwert", a: "2asdfg" },{ id: 3, q: "3qwert", a: "3asdfg" },{ id: 4, q: "4qwert", a: "4asdfg" },{ id: 5, q: "5qwert", a: "5asdfg" },{ id: 6, q: "6qwert", a: "6asdfg" },{ id: 7, q: "7qwert", a: "7asdfg" },{ id: 8, q: "8qwert", a: "8asdfg" },{id: 9,q: "9qwert",a: "9asdfg"}]};},methods: {setData: function(obj) {let that = this;let keys = [];let val, data;Object.keys(obj).forEach(function(key) {keys = key.split(".");val = obj[key];data = that.$data;keys.forEach(function(key2, index) {if (index + 1 == keys.length) {that.$set(data, key2, val);} else {if (!data[key2]) {that.$set(data, key2, {});}}data = data[key2];});});}}
};
</script>