我有三个lottie播放器json动画文件 - congratulations1.json、congratulations2.json 和 congratulations3.json 动画如下:
恭喜1:
<lottie-player
v-if="showPlayer1"
class="justify-content-center"
src="../../../congratulations.json"
background="transparent"
speed="1"
style="width: 300px; height: 300px"
loop
controls
autoplay
></lottie-player
>;
恭喜2:
<lottie-player
v-if="showPlayer2"
class="justify-content-center"
src="../../../congratulations2.json"
background="transparent"
speed="1"
style="width: 300px; height: 300px"
loop
controls
autoplay
></lottie-player
>;
恭喜3:
<lottie-player
v-if="showPlayer3"
class="justify-content-center"
src="../../../congratulations3.json"
background="transparent"
speed="1"
style="width: 300px; height: 300px"
loop
controls
autoplay
></lottie-player
>;
注意: json 文件的路径在这些lottie-player 标记的 src 中提到。
我想在单击单个按钮时随机显示它们。
我做过的事情:
我为这三个动画中的每一个采用了三个变量。变量为 - showPlayer1、showPlayer2 和 showPlayer3。 我将它们保存在名为 showPlayer 的数组中,并将它们的值设置为 false。我不知道我的程序是否正确。 接下来我不知道该怎么办。
我的阵列:
<script>
export default {
data() {
return {
showPlayer: [
(showPlayer1 = false),
(showPlayer2 = false),
(showPlayer3 = false),
],
};
},
我已经做到了这一点。我不知道在按钮标签内包含什么来从数组中随机显示这三个动画。请帮忙。
更新的代码:
<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> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
正如我在下面所展示的,还有多种其他方法可以实现这一目标。但如果你想像你建议的那样做,我不会使用 showPlayer 作为布尔数组,而是作为数字。
有多种方法可以解决这个问题。如果您只想使用一个组件并切换源,您可以执行以下操作: 首先,将组件的 src 设置为变量:
使用 data() 中的字符串设置一个数组,如下所示:
animations: [ '../../../congratulations.json', '../../../congratulations2.json', '../../../congratulations3.json', ], animationSrc: ''然后为 randomButton 设置一个方法,如下所示:
onRandomButtonPress() { this.animationSrc = this.animations[Math.floor(Math.random()*this.animations.length)]; },我很快就破解了一个codesandbox: https://codesandbox.io/s/elastic -dijkstra-o7ety?file=/src/components/HelloWorld.vue
你还可以使用vue中的:is属性来加载动态组件,并在代码中设置要加载哪个组件。 https://v2.vuejs.org/v2/guide/components-动态异步.html