针对您提到的“uni-app 考试评测系统”,以下是一个简化的代码案例,展示了如何使用uni-app框架构建一个基本的考试评测系统。这个示例将涵盖创建考试、显示题目、提交答案以及简单评分的功能。
1. 创建项目结构
首先,确保您已经安装了HBuilderX或其他支持uni-app的开发工具,并创建了一个新的uni-app项目。
项目结构示例:
/pages
/exam
exam.vue
/store
index.js // Vuex 状态管理
/static
// 静态资源
App.vue
main.js
2. 定义考试题目(静态数据)
在store/index.js
中定义Vuex状态管理,用于存储考试题目和答案:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
questions: [
{ id: 1, question: 'What is the capital of France?', options: ['A. Berlin', 'B. Madrid', 'C. Paris', 'D. Rome'], answer: 'C' },
// 更多题目...
],
userAnswers: {}
},
mutations: {
setUserAnswer(state, { questionId, answer }) {
Vue.set(state.userAnswers, questionId, answer);
}
},
actions: {},
getters: {
getQuestions: state => state.questions,
getUserAnswers: state => state.userAnswers,
calculateScore: (state) => {
let score = 0;
for (let question of state.questions) {
if (state.userAnswers[question.id] === question.answer) {
score++;
}
}
return score;
}
}
});
3. 创建考试页面
在pages/exam/exam.vue
中创建考试页面,展示题目并允许用户提交答案:
<template>
<view>
<block v-for="question in questions" :key="question.id">
<text>{{ question.question }}</text>
<radio-group @change="onAnswerChange($event, question.id)">
<label v-for="option in question.options" :key="option">
<radio :value="option">{{ option.split(' ')[1] }}</radio>
</label>
</radio-group>
</block>
<button @click="submitExam">Submit</button>
<text>Score: {{ score }}</text>
</view>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex';
export default {
computed: {
...mapState(['questions']),
...mapGetters(['getUserAnswers', 'calculateScore']),
score() {
return this.calculateScore;
}
},
methods: {
...mapMutations(['setUserAnswer']),
onAnswerChange(event, questionId) {
this.setUserAnswer({ questionId, answer: event.detail.value });
},
submitExam() {
// 提交逻辑,可添加API调用等
console.log('User Answers:', this.getUserAnswers);
}
}
};
</script>
这个简化的例子展示了如何使用uni-app和Vuex构建一个基本的考试评测系统。实际项目中,您可能需要根据具体需求添加更多功能,如从服务器加载题目、用户身份验证、更复杂的评分规则等。