vue雪花飘落完整代码
时间: 2023-02-05 15:56:07 浏览: 219
雪花飘落代码
这是一个使用 Vue.js 实现的雪花飘落效果的完整代码示例:
```
<template>
<div class="snowfall">
<div v-for="(flake, index) in flakes" :key="index" :style="{ top: flake.y + 'px', left: flake.x + 'px' }" class="flake">
{{ flake.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
flakes: [],
maxFlakes: 50,
minFlakeSize: 10,
maxFlakeSize: 20,
minSpeed: 1,
maxSpeed: 5,
};
},
mounted() {
this.createFlakes();
this.moveFlakes();
},
methods: {
createFlakes() {
for (let i = 0; i < this.maxFlakes; i++) {
let flakeSize = this.getRandom(this.minFlakeSize, this.maxFlakeSize);
let flakeSpeed = this.getRandom(this.minSpeed, this.maxSpeed);
let flake = {
x: this.getRandom(0, 100),
y: this.getRandom(-600, 0),
size: flakeSize,
text: '❄️',
speed: flakeSpeed,
};
this.flakes.push(flake);
}
},
moveFlakes() {
setInterval(() => {
for (let i = 0; i < this.flakes.length; i++) {
let flake = this.flakes[i];
flake.y += flake.speed;
if (flake.y > 600) {
this.flakes.splice(i, 1);
i--;
}
}
}, 50);
},
getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
},
};
</script>
<style>
.snowfall {
position: relative;
width: 100%;
height: 600px;
background: #000;
}
.flake {
position: absolute;
color: #fff;
font-size: 20px;
}
</style>
```
这段代码使用了 Vue 的指令 `v-for` 和 `v-bind` 来渲染每一片雪花,使用了 `setInterval` 函数来不断更新雪花的位置,并在雪花超出视窗时将它从数组中移除。
注意:
阅读全文