子组件代码
<template>
<view style="flex:1" >
<view class="flex flex-end" style="width: 100%">
<picker @change="handleChange" :value="index" :range="options" :range-key="rangeKey">
{{currentValue || placeholoder}}
</picker>
<slot></slot>
</view>
</view>
</template>
<script>
export default {
name: "CustomPicker",
props: {
value: String | Number,
options: Array,
rangeKey: String,
rangeValue: {
type: String,
default: "value"
},
placeholoder: {
type: String,
default: "请选择"
}
},
data() {
return {
index: -1
};
},
computed: {
currentValue() {
if (this.rangeKey) {
return this.index == -1 ? "" : this.options[this.index][this.rangeKey]
} else {
return this.options[this.index]
}
}
},
watch: {
value: {
immediate: true,
handler(val) {
this.index = this.rangeKey ? this.options.findIndex(item => item[this.rangeValue] === val) : this.options.findIndex(item => item === val);
}
}
},
methods: {
handleChange(e) {
this.index = e.target.value;
let currentValue = this.rangeKey ? this.options[this.index][this.rangeValue] : this.options[this.index];
this.$emit("input", currentValue)
this.$emit("change", currentValue)
},
}
}
</script>
<style lang="scss" scoped>
</style>
父组件调用
<u-form-item label="性别" prop="formData.sex">
<CustomPicker :options="options" v-model="formData.sex" rangeKey="label" :value="formData.sex">
<view class="flex flex-end">
<u-icon color="#C7C7CC" name="arrow-right"></u-icon>
</view>
</CustomPicker>
</u-form-item>
data(){
return {
options: [
{
value: 1,
label: "男"
},
{
value: 2,
label: "女"
}
],
formData:{sex:1}
}
}
评论 1 条评论
感谢,很有用