痛點

在項目經常會遇到這樣的設計,下拉選擇框,在
vant
中沒有提供直接的
select
組件,但是可以使用
Field
、
Popup
和
Picker
這三個組件組合來完成。
如果頁面中只有一個
select
這樣做做也還可以,但是現在頁面中有三個
select
就有點繁瑣了,所以考慮進行組件的封裝。
使用期望
<van-field-select-picker label="物料類型" placeholder="選擇類型" v-model="materielType" :columns="materielTypeList" />
我希望是在頁面中這樣使用組件
新建組件

在項目的
src/components
文件夾下面新建了一個
VanFieldSelectPicker.vue
文件,具體代碼如下,這里主要就是學習了一下組件嵌套時自定義
v-model
,組件中暫時也沒考慮太多其他的東西,有什么問題只能遇到了再更新。
<template> <div> <van-field v-model="result" v-bind="$attrs" readonly is-link @click="show = !show" /> <van-popup v-model="show" position="bottom"> <van-picker :columns="columns" show-toolbar :title="$attrs.label" @cancel="show = !show" @confirm="onConfirm" /> </van-popup> </div> </template> <script> export default { model: { prop: "selectValue" }, props: { columns: { type: Array }, selectValue: { type: String } }, data() { return { show: false, result: this.selectValue }; }, methods: { onConfirm(value) { this.result = value; this.show = !this.show; } }, watch: { selectValue: function(newVal) { this.result = newVal; }, result(newVal) { this.$emit("input", newVal); } } }; </script> <style></style>
效果
<van-field-select-picker label="物料類型" placeholder="請選擇" v-model="value1" :columns="[1, 2, 3]" /> <van-field-select-picker label="品牌" placeholder="請選擇" v-model="value2" :columns="[1, 2, 3]" /> <van-field-select-picker label="規格" placeholder="請選擇" v-model="value3" :columns="[1, 2, 3]" />

鏈接:https://www.jianshu.com/p/3c6609d5dad3
補充
實際應用中需要拿到下拉選擇的id值,但用上面封裝的只能拿到text,所以做了如下修改
1、組件SelectPicker.vue
<template> <div> <van-field v-model="result" v-bind="$attrs" readonly is-link @click="show = !show" /> <van-popup v-model="show" position="bottom"> <van-picker :columns="columns" show-toolbar :title="$attrs.label" @cancel="show = !show" @confirm="onConfirm" /> </van-popup> </div> </template> <script> export default { model: { prop: "selectValue" }, props: { columns: { type: Array }, selectValue: { type: String }, name:{ type: String //父組件傳進來一個name } }, data() { return { show: false, result: this.selectValue }; }, methods: { onConfirm(value) { this.result = value.label; this.show = !this.show; this.$emit("getMessage", this.name,value.value);//把value值傳給父組件 }, }, watch: { selectValue: function(newVal) { this.result = newVal; }, result(newVal) { this.$emit("input", newVal); } } }; </script> <style></style>
2、父組件
<template v-else-if="item.type.name == 'picklist' > <input type="hidden" value="" :id=item.name> <select-picker :label="item.label" :name="item.name" placeholder="請選擇" v-model="dataList[item.name]" :columns="item.type.picklistValues" @getMessage="setValue" /> </template>
<script>
export default {
data() {
return {
name:'',
}
},
methods: {
setValue(name,value){
$("#"+name).val(value);
},
},
}
</script>