环境:vue3,vant4
背景:Picker 作为用于辅助表单填写,搭配 Popup 和 Field 。页面需要给picker设置默认值,city为温州,但是在popup弹出时,picker没有选中温州这个选项,还时停留在杭州。
解决方案:
看了很多解决方案,设置default-indexset ,ColumnIndex。都尝试了,还是不行。而且这些方法,其实在vant4文档中,根本没有写。
很奇怪,后来想到了解决方案。
我设置了van-field的v-model,其实只改变了外部的值。
let formData = reactive({city:'温州'});
popup弹出时,picker的值其实没有改变,需要在van-picker上绑定v-model,设置初始值即可。van-data-picker, 也可以通过这种方式设置(亲测)
<van-popup v-model:show="showPicker" round position="bottom"> <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" v-model="defaultCity" /> </van-popup> const defaultCity = ref(['Wenzhou'])
具体完整代码如下:
<template> <van-cell-group> <van-field v-model="formData.city" is-link readonly label="城市" placeholder="选择城市" @click="showPicker = true" /> <van-popup v-model:show="showPicker" round position="bottom"> <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" v-model="defaultCity" /> </van-popup> </van-cell-group> </template>
<script setup> import { ref } from 'vue'; const columns = [ { text: '杭州', value: 'Hangzhou' }, { text: '宁波', value: 'Ningbo' }, { text: '温州', value: 'Wenzhou' }, { text: '绍兴', value: 'Shaoxing' }, { text: '湖州', value: 'Huzhou' }, ]; let formData = reactive({city:'温州'}); const defaultCity = ref(['Wenzhou']); const showPicker = ref(false); const onConfirm = ({ selectedOptions }) => { showPicker.value = false; formData.city = selectedOptions[0].text; }; </script>
标签:picker,Popup,const,text,value,vant4,默认值,ref From: https://www.cnblogs.com/Super-scarlett/p/17919981.html