vue实现gif动画
Vue 中实现 GIF 动画的方法
直接使用 <img> 标签加载 GIF
在 Vue 模板中直接通过 <img> 标签引入 GIF 文件,适用于静态 GIF 展示。
<template>
<img src="@/assets/example.gif" alt="GIF动画示例">
</template>
动态绑定 GIF 路径
通过 Vue 的响应式数据动态切换 GIF 路径,实现动态加载。

<template>
<img :src="currentGif" alt="动态GIF">
</template>
<script>
export default {
data() {
return {
currentGif: require('@/assets/default.gif')
}
},
methods: {
changeGif(newGif) {
this.currentGif = require(`@/assets/${newGif}.gif`);
}
}
}
</script>
使用 CSS 控制 GIF 播放
通过 CSS 的 animation 属性或 JavaScript 控制 GIF 的播放状态。

<template>
<div class="gif-container">
<img ref="gifImage" src="@/assets/animated.gif" alt="可控GIF">
<button @click="toggleGif">暂停/播放</button>
</div>
</template>
<script>
export default {
methods: {
toggleGif() {
const gif = this.$refs.gifImage;
gif.style.animationPlayState =
gif.style.animationPlayState === 'paused' ? 'running' : 'paused';
}
}
}
</script>
<style>
.gif-container img {
animation: play 1s steps(10) infinite;
}
@keyframes play {
from { background-position: 0; }
to { background-position: -1000px; }
}
</style>
使用第三方库(如 libgif)
对于需要精细控制的场景,可使用专门处理 GIF 的库。
<template>
<img ref="gifElement" src="@/assets/control.gif" alt="高级控制GIF">
<button @click="playGif">播放</button>
<button @click="pauseGif">暂停</button>
</template>
<script>
import SuperGif from 'libgif';
export default {
mounted() {
this.gifController = new SuperGif({ gif: this.$refs.gifElement });
this.gifController.load();
},
methods: {
playGif() {
this.gifController.play();
},
pauseGif() {
this.gifController.pause();
}
}
}
</script>
转换为 CSS 动画或 SVG 动画
对于简单动画,可考虑将 GIF 转换为 CSS 或 SVG 动画以获得更好性能。
<template>
<div class="css-animation"></div>
</template>
<style>
.css-animation {
width: 100px;
height: 100px;
background: url('@/assets/frames.png');
animation: play 0.8s steps(10) infinite;
}
@keyframes play {
from { background-position: 0; }
to { background-position: -1000px; }
}
</style>
注意事项
- 大尺寸 GIF 可能影响性能,建议优化帧率或尺寸
- 动态加载 GIF 时注意使用
require确保路径正确 - 考虑使用
v-if或v-show控制 GIF 的显隐以优化性能 - 移动端注意 GIF 的自动播放策略限制






