问题描述
小程序中引用uView ui 中select组件(单列模式)。出现第一次选择了列表中的某一项,再次唤起select组件时,直接点击确认。confirm事件返回的是列表中的第一项数据,而不是第一次选中的数据。
解决问题
需要用到select组件中的default-value参数和findIndex()数组方法。
- default-value:提供的默认选中的下标(index),传值为数组 例:[0]
- findIndex():返回数组中通过条件判断的第一个元素的索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <template> <view> <u-input v-model="station" type="select" placeholder="请选择站点" @click="showStation = true" /> <u-select v-model="showStation" :list="stationList" :default-value="selectDefault" @confirm="selectStation" /> </view> </template>
<script> export default { data() { return { station:'', showStation:false, selectDefault:[0], stationList:[ { name:'东站', value:'1001' }, { name:'西站', value:'1002' }, { name:'南站', value:'1003' }, { name:'北站', value:'1004' }, ] }; }, methods: { selectStation(val){ this.station = val[0].label; this.selectDefault = [this.stationList.findIndex(item => item.value === val[0].value)] || [0]; console.log(this.selectDefault) } } } </script>
|
如果选项列表的 value 值刚好与 选项列表的下标index相同时,可以直接将value以数组的形式赋值给selectDefault。不需要findIndex()的筛选操作。