我有以下代码。我想用随机选择的选项更新results-box
。如何在@click
事件上更新模板。
<template>
<div class="container">
<button @click="getDecision()" class="ui primary button">Discover</button>
<p id="results-box"></p>
</div>
</template>
<script>
export default {
name: "SlapButton",
data() {
return {
}
},
methods: {
getDecision: function () {
var decisions = [
"choice 1",
"choice 2",
"choice 3",
"choice 4",
"choice 5",
"choice 6"
]
var randNum = Math.floor((Math.random() * decisions.length) + 0);
var randChoice = decisions[randNum];
}
}
}
</script>
当用户点击按钮getDecision()
时,它会从decisions
数组中选择一个随机选项。如何在randChoice
代码p
中显示此随机选择#results-box
。
答案 0 :(得分:1)
尝试以下代码,请详细说明这是否有效:
<template>
<div class="container">
<button @click="getDecision" class="ui primary button">Discover</button>
<p id="results-box">
{{choice}}
</p>
</div>
</template>
<script>
export default {
name: "SlapButton",
data() {
return {
choice: '',
decisions = [
"choice 1",
"choice 2",
"choice 3",
"choice 4",
"choice 5",
"choice 6"
]
}
},
methods: {
getDecision() {
var randNum = Math.floor((Math.random() * this.decisions.length) + 0);
this.choice = this.decisions[randNum];
}
}
}
</script>
答案 1 :(得分:0)
基本上。一旦在randChoice
对象中定义了这个变量,你就需要一个能保持data (){}
的变量,只需在方法中给它一个值,如下所示:
export default {
name: "SlapButton",
data() {
return {
randomChoice: false
}
},
methods: {
getDecision: function () {
var decisions = [
"choice 1",
"choice 2",
"choice 3",
"choice 4",
"choice 5",
"choice 6"
]
var randNum = Math.floor((Math.random() * decisions.length) + 0);
this.randomChoice = decisions[randNum];
}
}
}
现在只需在您的元素中显示此数据:
<p id="results-box"> {{randomChoice}} </p>