<template> <div> <van-field @click="showPickerHandle" is-link v-model="name" :label="label" placeholder="请选择" :required="required" readonly :disabled="disabled"/> <van-popup v-model="showStatus" position="bottom" :close-on-click-overlay="false" custom-style="height: 30%;"> <van-picker show-toolbar :columns="columns" value-key="name" @cancel="onCancel" :visible-item-count="visibleCount" :default-index="defaultIndex" @confirm="onConfirm"/> </van-popup> </div></template><script>import { findIndex } from "@/utils/tool";export default { props: { value: { default: ''},// 必须要使用value list: { type: Array, default: [] }, visibleCount: { type: Number, default: 2 }, label: { type: String, default: ''}, required: { type: Boolean, default: false }, disabled: { type: Boolean, default: false } }, data() { return { showStatus: this.showPicker, columns: this.list, name: '' }; }, components: {}, created() { for(let i = 0; i < this.columns.length; i++) { if(this.columns[i].val === this.value) { this.name = this.columns[i].name; } } }, methods: { onCancel() { this.showStatus = false; this.$emit('cancel') }, // 控制选择器的弹出层 onConfirm(value, index) { // console.log(value); this.showStatus = false; this.name = value.name this.$emit('input',value.val); }, showPickerHandle(){ if(this.disabled){ return } this.showStatus = true; } }, computed: { defaultIndex () { if(this.value !==''){ return findIndex(this.value, this.columns); }else { return 0 } }, }, watch: { list(val) { this.columns = val; }, value: { deep: true, handler(val) { // console.log(val) if(val===''){ this.name = ''; }else{ for(let i = 0; i < this.columns.length; i++) { if(this.columns[i].val === val) { this.name = this.columns[i].name; } } } } } }}</script><style lang='less' scoped>.van-cell::after { position: absolute; box-sizing: border-box; content: ' '; pointer-events: none; right: 0; bottom: 0; left: 0.42667rem; border-bottom: 0.02667rem solid #ebedf0; -webkit-transform: scaleY(.5); transform: scaleY(.5);}</style>
list数据用的结构是这样的
// 性别export const sexList = [ { name: '男', val: 1 }, { name: '女', val: 0 }]
在父组件注册该组件后直接这样用,搞定!
<picker v-model="sex" :list="sexList " label="性别" :disabled="editable"></picker>