Vue 中可以使用JavaScript的Math.random() 函数生成随机数,它会返回 0 到 1 之间的浮点数,
如果需要0到1000之前的随机数,可以对生成的随机数乘以1000,再用js的向下取整函数Math.floor() 。
let randNum = Math.random(); // 生成0到1之间的随机数
let intRandNum=Math.floor(randNum * 1000); // 生成0到1000之间的随机整数
Math.floor() 是一个用于向下取整的函数,它通常用于将浮点数舍入为最接近但不大于原始值的整数。
完整示例:
<template>
<div>
<p>随机数: {{ intRandNum }}</p>
<button @click="handleClick">生成随机数</button>
</div>
</template>
<script>
export default {
data() {
return {
intRandNum: 0
}
},
methods: {
handleClick() {
let randNum = Math.random(); // 生成0到1之间的随机数
this.intRandNum=Math.floor(randNum * 1000); // 生成0到1000之间的随机整数
},
}
}
</script>