vue 实现选题操作
实现选题操作的基本思路
在Vue中实现选题操作通常涉及数据绑定、事件处理和状态管理。通过v-model或自定义事件实现双向绑定,结合数组或对象存储选中状态。
单选功能的实现
使用v-model绑定单个变量存储选中项的ID或值。适用于只能选择一个选项的场景。
<template>
<div>
<div v-for="item in options" :key="item.id">
<input
type="radio"
:id="item.id"
:value="item.id"
v-model="selectedItem"
>
<label :for="item.id">{{ item.text }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItem: null
}
}
}
</script>
多选功能的实现
使用数组存储多个选中项,通过v-model绑定到checkbox的value属性。
<template>
<div>
<div v-for="item in options" :key="item.id">
<input
type="checkbox"
:id="item.id"
:value="item.id"
v-model="selectedItems"
>
<label :for="item.id">{{ item.text }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItems: []
}
}
}
</script>
自定义选择组件
封装可复用的选择组件,通过props接收选项数据,通过emit事件传递选择结果。
<!-- Selector.vue -->
<template>
<ul>
<li
v-for="item in items"
:key="item.value"
@click="selectItem(item)"
:class="{ active: isSelected(item) }"
>
{{ item.label }}
</li>
</ul>
</template>
<script>
export default {
props: {
items: Array,
value: [Array, String, Number]
},
methods: {
isSelected(item) {
return Array.isArray(this.value)
? this.value.includes(item.value)
: this.value === item.value
},
selectItem(item) {
this.$emit('input', item.value)
}
}
}
</script>
使用计算属性处理选择结果
通过计算属性对选择结果进行过滤或格式化处理。
computed: {
selectedOptions() {
return this.options.filter(option =>
this.selectedItems.includes(option.id)
)
},
selectionCount() {
return this.selectedItems.length
}
}
与Vuex集成管理选择状态
对于复杂应用,可以使用Vuex集中管理选择状态。
// store.js
export default new Vuex.Store({
state: {
selections: []
},
mutations: {
addSelection(state, item) {
state.selections.push(item)
},
removeSelection(state, itemId) {
state.selections = state.selections.filter(i => i.id !== itemId)
}
}
})
响应式样式处理
根据选择状态动态添加CSS类,增强用户体验。
<li
v-for="item in items"
:class="{ 'selected': selectedItems.includes(item.id) }"
@click="toggleSelection(item)"
>
{{ item.name }}
</li>
.selected {
background-color: #f0f0f0;
border-left: 3px solid #42b983;
}
性能优化建议
对于大型选项列表,使用虚拟滚动技术避免渲染所有DOM节点。

<template>
<RecycleScroller
:items="largeOptions"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div @click="selectItem(item)">
{{ item.text }}
</div>
</template>
</RecycleScroller>
</template>






