vue实现picker
Vue 实现 Picker 组件
使用原生 HTML 和 Vue 实现基础 Picker
通过 <select> 和 <option> 标签结合 Vue 的 v-model 实现数据绑定:
<template>
<select v-model="selectedOption">
<option v-for="option in options" :value="option.value">
{{ option.text }}
</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ text: '选项1', value: '1' },
{ text: '选项2', value: '2' }
]
}
}
}
</script>
使用第三方库(如 Vant)
Vant 提供了现成的 Picker 组件,支持多列选择和复杂数据:
<template>
<van-picker
v-model="selectedValue"
:columns="columns"
@confirm="onConfirm"
/>
</template>
<script>
import { Picker } from 'vant';
export default {
components: { 'van-picker': Picker },
data() {
return {
selectedValue: '',
columns: ['杭州', '宁波', '温州']
}
},
methods: {
onConfirm(value) {
console.log('选择的值:', value);
}
}
}
</script>
自定义 Picker 组件
通过 CSS 和 Vue 事件实现滚动选择器:
<template>
<div class="custom-picker">
<div
v-for="item in items"
:key="item"
@click="selectItem(item)"
:class="{ selected: item === selectedItem }"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedItem: null,
items: ['选项A', '选项B', '选项C']
}
},
methods: {
selectItem(item) {
this.selectedItem = item;
this.$emit('select', item);
}
}
}
</script>
<style>
.custom-picker {
display: flex;
flex-direction: column;
max-height: 200px;
overflow-y: auto;
}
.custom-picker div {
padding: 10px;
cursor: pointer;
}
.custom-picker .selected {
background-color: #f0f0f0;
}
</style>
移动端优化方案
针对移动端触摸事件实现平滑滚动:
// 在自定义组件中添加触摸事件处理
mounted() {
this.$el.addEventListener('touchstart', this.handleTouchStart);
this.$el.addEventListener('touchmove', this.handleTouchMove);
},
methods: {
handleTouchStart(e) {
this.startY = e.touches[0].clientY;
},
handleTouchMove(e) {
const deltaY = e.touches[0].clientY - this.startY;
this.$el.scrollTop -= deltaY;
this.startY = e.touches[0].clientY;
}
}
性能优化建议
对于大型数据集考虑虚拟滚动技术:
// 使用 vue-virtual-scroller 等库
import { RecycleScroller } from 'vue-virtual-scroller';
components: {
RecycleScroller
},
// 模板中使用
<RecycleScroller
:items="largeData"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div @click="selectItem(item)">{{ item.name }}</div>
</RecycleScroller>






