思路:首先设置变量获取到随机生成的数字。设置一个空数组。然后for循环,每一次都在空数组中添加数字1(任何都行,把 i 添加进去也行,主要是为了撑开空数组,让空数组的length长度等于我们生成的随机数,这样遍历渲染的时候,div个数才会跟数组的长度一致)。数组为空的目的是为了每一次页面重绘都是最新的,不会叠加。
具体代码如下:
<template>
<div>
<button @click="btn">BUTTON</button>
<div v-for="(item, index) in arr2" :key="index" id="red"></div>
</div>
</template>
<script>
export default {
props: {},
data() {
return {
num: "",
arr2: [],
};
},
methods: {
btn() {
this.num = Math.ceil(Math.floor(parseInt(Math.random() * 5) + 1));
this.arr2=[]
for (var i = 0; i < this.num; i++) {
this.arr2.push(1);
}
},
},
components: {},
};
</script>
<style scoped lang="less">
button {
padding: 30px;
background-color: pink;
}
#red{
width: 100px;
height: 50px;
margin-top: 30px;
background-color: blue;
}
</style>