vue 实现选题操作
实现选题操作的基本思路
在Vue中实现选题操作通常涉及数据绑定、事件处理和状态管理。通过v-model或自定义事件实现选项的选择与反选,结合计算属性或方法动态更新选中状态。
单选功能实现
使用v-model绑定单个选项值,适用于单选场景。定义选项数组和选中值,通过单选框或下拉菜单实现选择。
<template>
<div>
<select v-model="selectedOption">
<option v-for="option in options" :value="option.value" :key="option.value">
{{ option.label }}
</option>
</select>
<p>当前选择: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' }
],
selectedOption: ''
}
}
}
</script>
多选功能实现
使用数组类型的数据绑定多选值,通过复选框实现多选。v-model绑定到数组会自动处理选中状态的增减。
<template>
<div>
<div v-for="option in options" :key="option.value">
<input
type="checkbox"
:id="option.value"
:value="option.value"
v-model="selectedOptions"
>
<label :for="option.value">{{ option.label }}</label>
</div>
<p>已选择: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' }
],
selectedOptions: []
}
}
}
</script>
自定义选择逻辑
对于复杂选择逻辑,可使用方法处理选中状态。维护一个选中项数组,通过点击事件切换选中状态。
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="toggleSelect(item.id)"
:class="{ selected: selectedItems.includes(item.id) }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '项目1' },
{ id: 2, text: '项目2' }
],
selectedItems: []
}
},
methods: {
toggleSelect(id) {
const index = this.selectedItems.indexOf(id)
if (index === -1) {
this.selectedItems.push(id)
} else {
this.selectedItems.splice(index, 1)
}
}
}
}
</script>
<style>
.selected {
background-color: #eee;
}
</style>
使用Vuex管理选中状态
在大型应用中,使用Vuex集中管理选中状态更合适。定义state存储选中数据,通过mutations和actions更新状态。
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
selectedItems: []
},
mutations: {
TOGGLE_ITEM(state, itemId) {
const index = state.selectedItems.indexOf(itemId)
if (index === -1) {
state.selectedItems.push(itemId)
} else {
state.selectedItems.splice(index, 1)
}
}
},
actions: {
toggleItem({ commit }, itemId) {
commit('TOGGLE_ITEM', itemId)
}
}
})
组件中通过mapState和mapActions访问和修改选中状态:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="toggleItem(item.id)"
:class="{ selected: selectedItems.includes(item.id) }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState(['selectedItems'])
},
methods: {
...mapActions(['toggleItem'])
}
}
</script>
性能优化建议
对于大量选项的场景,考虑使用虚拟滚动技术减少DOM节点。可采用第三方库如vue-virtual-scroller实现高效渲染。
<template>
<RecycleScroller
class="scroller"
:items="largeList"
:item-size="32"
key-field="id"
v-slot="{ item }"
>
<div
@click="toggleSelect(item.id)"
:class="{ selected: selectedItems.includes(item.id) }"
>
{{ item.text }}
</div>
</RecycleScroller>
</template>






