用vue随机生成五道数学题
时间: 2023-07-12 08:47:05 浏览: 272
几个简单的vue面试题
好的,下面是使用Vue.js随机生成五道数学题的示例代码:
HTML部分:
```html
<div id="app">
<h1>随机生成五道数学题</h1>
<ul>
<li v-for="(question, index) in questions">
<span>{{ index + 1 }}. {{ question.expression }}</span>
<input type="text" v-model="question.answer" />
</li>
</ul>
<button @click="submit">提交答案</button>
</div>
```
Vue.js部分:
```javascript
new Vue({
el: "#app",
data: {
questions: [
{
expression: "",
answer: ""
},
{
expression: "",
answer: ""
},
{
expression: "",
answer: ""
},
{
expression: "",
answer: ""
},
{
expression: "",
answer: ""
}
]
},
methods: {
generateQuestion() {
const operators = ["+", "-", "*", "/"];
const maxNumber = 100;
for (let i = 0; i < this.questions.length; i++) {
const operator = operators[Math.floor(Math.random() * operators.length)];
let number1 = Math.floor(Math.random() * maxNumber) + 1;
let number2 = Math.floor(Math.random() * maxNumber) + 1;
if (operator === "/") {
number1 = number1 * number2;
}
const expression = `${number1} ${operator} ${number2} = `;
this.questions[i].expression = expression;
this.questions[i].answer = "";
}
},
submit() {
let correct = 0;
for (let i = 0; i < this.questions.length; i++) {
const question = this.questions[i];
const expression = question.expression.replace("=", "");
const answer = question.answer;
if (eval(expression) === Number(answer)) {
correct++;
}
}
alert(`你答对了 ${correct} 道题目`);
}
},
mounted() {
this.generateQuestion();
}
});
```
这个示例会在页面中显示五道数学题,每道题目都包含一个表达式和一个文本框,用户可以在文本框中输入答案。当用户点击提交答案按钮时,程序会遍历所有的题目,计算表达式的值,然后和用户输入的答案进行比较,最后弹出一个提示框告诉用户答对了多少道题目。
阅读全文