我今天遇到了一个小bug也是困扰绕了我许久。就是我用HbuilderX写一个小程序,然后需要写一个城市选择器功能,我当时用的是uview-plus组件库,但是他的城市选择器在当时有bug,官方示例运行起来都报错。没有黑他的意思,但真不是我的原因。于是在网上找了一个,感觉还不错,就拿来用了,你们也可以直接下载js文件拿来直接用。
这是一个城市选择器的数据,注意我的文件路径。 我把文件放在了components文件夹下面整成了一个组件。然而bug是啥呢!
city.js 文件pan.baidu.com/s/1RzhI4JqJ…
<template>
<view>
<button @click.stop="show = true">城市选择器</button>
<!-- 城市选择器 -->
<u-picker :show="show" ref="uPicker" :columns="cityList" @confirm="confirm" @change="changeHandler" @cancel="show = false"></u-picker>
</view>
</template>
<script>
// 导入城市js文件 这里引用的路径是没错的
import cityData from '../../utils/city.js'
export default {
data() {
return {
//显示选择器
show: false,
// 打开选择器显示默认城市
cityList: [],
cityLevel1: [],
cityLevel2: [],
cityLevel3: []
}
},
onLoad(){
//城市选择器初始化
this.initCityData();
},
methods: {
initCityData(){
// 遍历城市js
cityData.forEach((item1, index1) =>{
let temp2 = [];
this.cityLevel1.push(item1.provinceName);
let temp4 = [];
let temp3 = [];
// 遍历市
item1.cities.forEach((item2, index2) =>{
temp2.push(item2.cityName);
// 遍历区
item2.counties.forEach((item3, index3) =>{
temp3.push(item3.countyName);
})
temp4[index2] = temp3;
temp3 = [];
})
this.cityLevel3[index1] = temp4;
this.cityLevel2[index1] = temp2;
})
// 选择器默认城市
this.cityList.push(this.cityLevel1,this.cityLevel2[0],this.cityLevel3[0][0]);
},
// 选中时执行
changeHandler(e) {
const {
columnIndex,
index,
indexs,
value,
values,
// 微信小程序无法将picker实例传出来,只能通过ref操作
picker = this.$refs.uPicker
} = e;
if (columnIndex === 0) { // 选择第一列数据时
// 设置第二列关联数据
picker.setColumnValues(1, this.cityLevel2[index]);
// 设置第三列关联数据
picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
}else if(columnIndex === 1){// 选择第二列数据时
// 设置第三列关联数据
picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
}
},
// 单击确认按钮时执行
confirm(e) {
// 输出数组 [省, 市, 区]
console.log(e.value);
// 隐藏城市选择器
this.show = false;
}
}
}
</script>
pages页面里面直接就拿来用了注册使用了,运行起啦发现数据JS数据没加载出来
得到的页面是这样的
排查了一会在一位博主那里找到了原因,components 引入的文件作为子组件,其加载的有些生命周期不会执行,如果页面有需要预加载数据的,建议放在 created 中进行接口数据请求,而不是使用 onLoad、onReady 等钩子。 最后解决方法就是把onload换成了created函数,数据成功渲染。
如何以上没有问题可以检查一下 如果引入不成功则考虑以下几个问题:
- 是 components 而非 component
- 导入后的命名方式采用驼峰命名法
- 检查需要引入的文件路径和文件名是否正确