vue实现gif动画
Vue 中实现 GIF 动画的方法
方法一:直接使用 <img> 标签引入 GIF
在 Vue 模板中直接通过 <img> 标签加载 GIF 文件,适合静态展示。
<template>
<img src="@/assets/example.gif" alt="GIF动画" />
</template>
方法二:动态绑定 GIF 路径 通过 Vue 的响应式数据动态切换 GIF 路径,实现灵活控制。
<template>
<img :src="currentGif" alt="动态GIF" />
<button @click="changeGif">切换GIF</button>
</template>
<script>
export default {
data() {
return {
gifs: [
require('@/assets/gif1.gif'),
require('@/assets/gif2.gif')
],
currentIndex: 0
}
},
computed: {
currentGif() {
return this.gifs[this.currentIndex];
}
},
methods: {
changeGif() {
this.currentIndex = (this.currentIndex + 1) % this.gifs.length;
}
}
};
</script>
方法三:结合 CSS 控制播放
通过 CSS 的 animation 或 transition 控制 GIF 的播放状态,例如暂停/播放。

<template>
<div class="gif-container">
<img
src="@/assets/example.gif"
:style="{ animationPlayState: isPlaying ? 'running' : 'paused' }"
/>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
isPlaying: true
}
},
methods: {
togglePlay() {
this.isPlaying = !this.isPlaying;
}
}
};
</script>
<style>
.gif-container img {
animation: playGif 1s infinite;
}
@keyframes playGif {
from { background-position: 0; }
to { background-position: 100%; }
}
</style>
方法四:使用第三方库(如 libgif.js) 对于需要控制 GIF 帧的高级需求,可以集成 libgif.js 等库。
-
安装依赖:

npm install libgif-js -
在组件中使用:
<template> <div ref="gifElement"></div> <button @click="playGif">播放</button> </template>
注意事项
- 性能优化:大尺寸 GIF 可能导致性能问题,建议压缩或使用视频替代。
- 动态加载:通过
require或动态导入确保构建工具正确处理路径。 - 响应式设计:为 GIF 容器设置固定宽高以避免布局抖动。






