Vue.js中实现点击按钮随机展示Lottie动画的问题咨询
解决方案
你后续调整的用单个showPlayer变量匹配数字判断显示的思路更简洁,只需要修正data定义、补充按钮点击逻辑即可,完整实现代码如下:
1. 模板部分(含触发按钮)
<!-- 触发按钮 --> <button @click="randomShowLottie">随机播放动画</button> <!-- 动画容器,和你现有代码一致即可 --> <div class="justify-content-center anim"> <lottie-player v-if="showPlayer === 1" class="justify-content-center" src="../../../congratulations.json" background="transparent" speed="1" style="width: 300px; height: 300px" loop controls autoplay ></lottie-player> </div> <div class="justify-content-center anim"> <lottie-player v-if="showPlayer === 2" class="justify-content-center" src="../../../congratulations_2.json" background="transparent" speed="1" style="width: 300px; height: 300px" loop controls autoplay ></lottie-player> </div> <div class="justify-content-center anim"> <lottie-player v-if="showPlayer === 3" class="justify-content-center" src="../../../congratulations_3.json" background="transparent" speed="1" style="width: 300px; height: 300px" loop controls autoplay ></lottie-player> </div>
2. 脚本部分
<script> export default { data() { return { // 初始值设为0,默认不显示任何动画 showPlayer: 0 } }, methods: { randomShowLottie() { // 生成1-3的随机整数,对应三个动画 this.showPlayer = Math.floor(Math.random() * 3) + 1 } } } </script>
说明
你最初定义数组的写法不符合Vue data的声明规范,强行用数组实现反而需要额外遍历修改状态,不如单个变量控制的方案高效。如果需要每次点击先隐藏之前的动画再加载新的,只需要在赋值前加一行this.showPlayer = 0,等DOM更新后再赋值新的随机数即可。
可选优化(减少冗余代码)
如果后续要新增动画,也可以把动画配置存为数组,用v-for渲染,不用重复写lottie-player标签:
<template> <button @click="randomShowLottie">随机播放动画</button> <div class="justify-content-center anim" v-for="item in lottieList" :key="item.id"> <lottie-player v-if="showPlayer === item.id" class="justify-content-center" :src="item.src" background="transparent" speed="1" style="width: 300px; height: 300px" loop controls autoplay ></lottie-player> </div> </template> <script> export default { data() { return { showPlayer: 0, lottieList: [ {id:1, src:'../../../congratulations.json'}, {id:2, src:'../../../congratulations_2.json'}, {id:3, src:'../../../congratulations_3.json'}, ] } }, methods: { randomShowLottie() { this.showPlayer = Math.floor(Math.random() * this.lottieList.length) + 1 } } } </script>
内容的提问来源于stack exchange,提问作者alprazolam
相关产品推荐
相关产品推荐

