vue实现填空
Vue 实现填空题功能
在 Vue 中实现填空题功能可以通过数据绑定和动态渲染来实现。以下是一种常见的实现方式:
数据准备
定义题目数据,包含题干和填空位置:
data() {
return {
questions: [
{
text: 'Vue 是一个 __1__ 框架,由 __2__ 开发',
blanks: ['', '']
}
]
}
}
模板渲染
使用 v-for 循环渲染题目,并用 v-model 绑定填空输入:
<div v-for="(question, qIndex) in questions" :key="qIndex">
<p v-html="renderQuestion(question)"></p>
<div v-for="(blank, bIndex) in question.blanks" :key="bIndex">
<input v-model="question.blanks[bIndex]" placeholder="请输入答案">
</div>
</div>
处理方法
添加方法处理题干渲染和答案验证:
methods: {
renderQuestion(question) {
let parts = question.text.split(/__\d+__/);
let result = '';
parts.forEach((part, index) => {
result += part;
if (index < parts.length - 1) {
result += `<span class="blank">${question.blanks[index] || '______'}</span>`;
}
});
return result;
},
checkAnswers() {
const correctAnswers = ['JavaScript', '尤雨溪'];
this.questions[0].blanks.forEach((answer, index) => {
if (answer === correctAnswers[index]) {
console.log(`第 ${index + 1} 空正确`);
} else {
console.log(`第 ${index + 1} 空错误`);
}
});
}
}
样式增强
添加 CSS 美化填空题样式:
.blank {
display: inline-block;
min-width: 80px;
border-bottom: 1px solid #333;
margin: 0 5px;
text-align: center;
}
input {
margin: 10px 0;
padding: 5px;
border: 1px solid #ddd;
border-radius: 4px;
}
动态填空题
如果需要更动态的填空题生成,可以使用正则表达式匹配:

generateBlanks(text) {
const blankRegex = /__\d+__/g;
const blankCount = (text.match(blankRegex) || []).length;
return Array(blankCount).fill('');
}
这种实现方式允许灵活地定义填空题,支持多个填空位置,并能方便地验证用户输入。可以根据实际需求调整样式和交互逻辑。






