vue 动画 枫叶下落 消失 再显示 代码
时间: 2024-05-01 10:17:35 浏览: 7
好的,以下是实现 Vue 动画枫叶下落消失再显示的代码:
HTML 代码如下:
```html
<template>
<div id="app">
<transition-group name="leaf-fall" tag="div">
<div v-for="(item, index) in leafList" :key="item.id" class="leaf-box">
<div class="leaf" :style="{ top: item.top + 'px', left: item.left + 'px' }"></div>
</div>
</transition-group>
</div>
</template>
```
CSS 样式如下:
```css
.leaf-fall-enter-active,
.leaf-fall-leave-active {
transition: all 1s ease;
}
.leaf-fall-enter,
.leaf-fall-leave-to {
opacity: 0;
transform: translateY(50px);
}
```
JavaScript 代码如下:
```js
export default {
data() {
return {
leafList: [], //存放落叶的数组
id: 0, //每个落叶的id
};
},
methods: {
init() {
//创建落叶
const leafBox = document.querySelector(".leaf-box");
const leafWidth = leafBox.offsetWidth;
const leafHeight = leafBox.offsetHeight;
const bodyWidth = document.body.clientWidth;
for (let i = 0; i < 5; i++) {
const id = this.id;
const left = Math.random() * (bodyWidth - leafWidth);
const top = -Math.random() * leafHeight - 20;
this.leafList.push({
id,
left,
top,
});
this.id++;
}
},
},
mounted() {
//初始化
this.init();
//每隔一段时间创建一片落叶
setInterval(() => {
this.init();
}, 3000);
},
};
```
需要注意的是,在 Vue 中使用动画,需要先引入 Vue 的动画模块,即在 main.js 中添加以下代码:
```js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
Vue.config.productionTip = false;
//引入动画模块
import "animate.css";
import "./assets/css/index.css"; //引入样式文件
Vue.prototype.$duration = 1000; //定义了一个全局变量,表示动画时长
new Vue({
router,
render: (h) => h(App),
}).$mount("#app");
```
然后在组件的 style 标签中引入 animate.css 文件,如下所示:
```css
@import "~animate.css/animate.css";
```
最后,在组件的 CSS 中添加动画的样式即可。