vue实现多填空
Vue 实现多填空功能
在 Vue 中实现多填空功能可以通过动态绑定和条件渲染来实现。以下是一个完整的实现方案:
动态绑定输入框
使用 v-model 绑定每个填空的输入值,通过数组或对象存储多个填空的值:
<template>
<div v-for="(blank, index) in blanks" :key="index">
<input v-model="blank.value" :placeholder="blank.placeholder">
</div>
</template>
<script>
export default {
data() {
return {
blanks: [
{ value: '', placeholder: '填空1' },
{ value: '', placeholder: '填空2' }
]
}
}
}
</script>
动态添加和删除填空
通过方法动态管理填空的数量:
<template>
<div>
<button @click="addBlank">添加填空</button>
<div v-for="(blank, index) in blanks" :key="index">
<input v-model="blank.value">
<button @click="removeBlank(index)">删除</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
blanks: [{ value: '' }]
}
},
methods: {
addBlank() {
this.blanks.push({ value: '' })
},
removeBlank(index) {
this.blanks.splice(index, 1)
}
}
}
</script>
填空题验证
添加验证逻辑确保所有填空都已填写:
<template>
<div>
<div v-for="(blank, index) in blanks" :key="index">
<input v-model="blank.value" required>
</div>
<button @click="submit">提交</button>
<p v-if="error" class="error">{{ error }}</p>
</div>
</template>
<script>
export default {
data() {
return {
blanks: [{ value: '' }],
error: ''
}
},
methods: {
submit() {
this.error = ''
const isEmpty = this.blanks.some(blank => !blank.value.trim())
if (isEmpty) {
this.error = '请填写所有空白处'
return
}
// 提交逻辑
}
}
}
</script>
填空题自动编号
为每个填空添加自动编号:
<template>
<div v-for="(blank, index) in blanks" :key="index">
<span>{{ index + 1 }}.</span>
<input v-model="blank.value">
</div>
</template>
填空题答案比对
实现用户答案与标准答案的比对功能:
<template>
<div>
<div v-for="(blank, index) in blanks" :key="index">
<input v-model="blank.userAnswer">
<span v-if="blank.correct !== undefined">
{{ blank.correct ? '✓' : '✗' }}
</span>
</div>
<button @click="checkAnswers">检查答案</button>
</div>
</template>
<script>
export default {
data() {
return {
blanks: [
{ userAnswer: '', correctAnswer: 'vue' },
{ userAnswer: '', correctAnswer: 'react' }
]
}
},
methods: {
checkAnswers() {
this.blanks.forEach(blank => {
blank.correct = blank.userAnswer === blank.correctAnswer
})
}
}
}
</script>
填空题样式优化
添加 CSS 样式提升用户体验:

<template>
<div class="blank-container">
<div v-for="(blank, index) in blanks" :key="index" class="blank-item">
<input v-model="blank.value" class="blank-input">
</div>
</div>
</template>
<style>
.blank-container {
margin: 20px;
}
.blank-item {
margin-bottom: 10px;
}
.blank-input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
以上方法可以根据实际需求组合使用,实现各种复杂的多填空场景。通过 Vue 的响应式特性,可以轻松管理多个填空的状态和交互。






