vue实现投票
Vue 实现投票功能
基本结构设计
使用 Vue.js 创建一个投票组件,包含投票选项和投票按钮。通过 v-for 动态渲染选项列表,v-model 绑定用户选择的数据。

<template>
<div class="vote-container">
<h3>{{ title }}</h3>
<ul>
<li v-for="(option, index) in options" :key="index">
<input
type="radio"
:id="'option-' + index"
:value="index"
v-model="selectedOption"
>
<label :for="'option-' + index">{{ option.text }}</label>
</li>
</ul>
<button @click="submitVote">提交投票</button>
<div v-if="showResult">
<h4>投票结果</h4>
<ul>
<li v-for="(option, index) in options" :key="index">
{{ option.text }}: {{ option.votes }}票
</li>
</ul>
</div>
</div>
</template>
数据与逻辑处理
在 script 部分定义投票数据和方法。使用 data 初始化选项列表和用户选择,通过 methods 实现投票提交逻辑。

<script>
export default {
data() {
return {
title: '请选择您最喜欢的框架',
options: [
{ text: 'Vue', votes: 0 },
{ text: 'React', votes: 0 },
{ text: 'Angular', votes: 0 }
],
selectedOption: null,
showResult: false
}
},
methods: {
submitVote() {
if (this.selectedOption !== null) {
this.options[this.selectedOption].votes++
this.showResult = true
} else {
alert('请先选择一个选项')
}
}
}
}
</script>
样式优化
添加 CSS 美化投票界面,确保选项布局清晰,按钮交互友好。
<style scoped>
.vote-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #eee;
border-radius: 8px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
}
button {
background-color: #42b983;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #369f6b;
}
</style>
进阶功能扩展
- 防止重复投票
使用localStorage记录用户投票状态,避免重复提交。
methods: {
submitVote() {
if (localStorage.getItem('hasVoted')) {
alert('您已经投过票了')
return
}
if (this.selectedOption !== null) {
this.options[this.selectedOption].votes++
this.showResult = true
localStorage.setItem('hasVoted', 'true')
}
}
}
- 实时数据同步
结合 Firebase 或 WebSocket 实现多客户端实时结果更新。
import { db } from './firebase'
methods: {
async submitVote() {
await db.collection('votes').doc(this.selectedOption).update({
votes: firebase.firestore.FieldValue.increment(1)
})
}
}
- 图表展示结果
引入 ECharts 或 Chart.js 将投票数据可视化。
import * as echarts from 'echarts'
mounted() {
if (this.showResult) {
const chart = echarts.init(document.getElementById('chart'))
chart.setOption({
xAxis: { data: this.options.map(o => o.text) },
yAxis: { type: 'value' },
series: [{ data: this.options.map(o => o.votes), type: 'bar' }]
})
}
}
注意事项
- 单选框绑定需确保
v-model和value类型一致 - 未选择选项时应给予明确提示
- 生产环境需结合后端验证投票合法性






