vue实现填空答题功能
Vue 实现填空答题功能
数据绑定与动态渲染
使用 Vue 的 v-model 实现填空题输入框的双向绑定。通过 v-for 动态渲染题目和填空区域,数据存储在组件的 data 中。
<template>
<div v-for="(question, index) in questions" :key="index">
<p v-html="renderQuestion(question.text)"></p>
<input
v-model="question.userAnswer"
:placeholder="'填空 ' + (index + 1)"
>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{ text: 'Vue的核心特性是__1__', userAnswer: '' },
{ text: '双向绑定通过__2__指令实现', userAnswer: '' }
]
}
},
methods: {
renderQuestion(text) {
return text.replace(/__\d+__/g, '<span class="blank"></span>');
}
}
};
</script>
填空题模板解析
通过正则表达式替换题目中的占位符(如 __1__)为空白输入框。使用 v-html 渲染处理后的 HTML,注意对用户输入进行安全过滤。
methods: {
renderQuestion(text) {
// 实际项目中需对用户输入做XSS过滤
return text.replace(/__\d+__/g, '<span class="blank"></span>');
}
}
答案校验功能
添加校验按钮和方法,对比用户答案与预设答案。可通过计算属性实时验证或手动触发验证。
data() {
return {
answers: { 1: '响应式', 2: 'v-model' },
showResult: false
}
},
methods: {
checkAnswers() {
this.showResult = true;
this.questions.forEach(q => {
const blankNum = q.text.match(/__(\d+)__/)[1];
q.isCorrect = q.userAnswer === this.answers[blankNum];
});
}
}
样式与交互优化
为填空区域和验证结果添加视觉反馈,使用 CSS 增强用户体验。
.blank {
border-bottom: 2px dashed #ccc;
padding: 0 0.5em;
}
input {
border: 1px solid #ddd;
padding: 0.5em;
}
.correct { color: green; }
.incorrect { color: red; }
动态题目加载
从后端 API 获取题目数据时,使用生命周期钩子或异步方法加载。
async created() {
try {
const res = await axios.get('/api/questions');
this.questions = res.data.map(q => ({
...q,
userAnswer: ''
}));
} catch (error) {
console.error('加载题目失败:', error);
}
}
可复用组件设计
将填空题封装为独立组件,通过 props 接收题目数据,emit 提交答案事件。
// FillBlank.vue
props: {
question: {
type: Object,
required: true
}
},
emits: ['answer-change']
状态管理
对于复杂应用,使用 Vuex 或 Pinia 集中管理答题状态和进度。
// store.js
state: {
questions: [],
currentIndex: 0
},
mutations: {
setAnswer(state, { index, answer }) {
state.questions[index].userAnswer = answer;
}
}






