vue实现投票
Vue实现投票功能
数据准备
在Vue组件的data中定义投票相关数据,包括选项列表和当前选中状态:
data() {
return {
options: [
{ id: 1, text: '选项A', votes: 0 },
{ id: 2, text: '选项B', votes: 0 },
{ id: 3, text: '选项C', votes: 0 }
],
selectedOption: null,
hasVoted: false
}
}
模板渲染
使用v-for渲染投票选项,v-model绑定选中状态:
<div v-for="option in options" :key="option.id">
<input
type="radio"
:id="'option'+option.id"
:value="option.id"
v-model="selectedOption"
:disabled="hasVoted">
<label :for="'option'+option.id">{{ option.text }}</label>
<span v-if="hasVoted">(得票: {{ option.votes }})</span>
</div>
投票逻辑
添加投票方法,处理投票提交:
methods: {
submitVote() {
if (!this.selectedOption || this.hasVoted) return
const selected = this.options.find(opt => opt.id === this.selectedOption)
if (selected) {
selected.votes++
this.hasVoted = true
// 可添加API调用保存投票结果
}
}
}
结果展示
添加投票按钮和结果显示:
<button @click="submitVote" :disabled="!selectedOption || hasVoted">
{{ hasVoted ? '已投票' : '提交投票' }}
</button>
<div v-if="hasVoted">
<h3>投票结果</h3>
<ul>
<li v-for="option in options" :key="option.id">
{{ option.text }}: {{ option.votes }}票
</li>
</ul>
</div>
样式优化
添加基础CSS样式增强用户体验:
div {
margin: 10px 0;
}
button {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
button:disabled {
background: #ccc;
}
持久化存储
如需保存投票结果到后端,可添加axios请求:
import axios from 'axios'
methods: {
async submitVote() {
// ...原有逻辑
try {
await axios.post('/api/vote', {
optionId: this.selectedOption
})
} catch (error) {
console.error('保存投票失败', error)
}
}
}






