- 安装第三方库
- 使用 npm 安装 Swiper,在项目根目录下运行命令:
npm install swiper@8.4.6
(这里指定版本号 8.4.6 为例,可根据实际情况调整)。
- 在 Vue 组件中引入并配置
- 全局引入:在
main.js
中引入 Swiper 及其样式。
import Vue from 'vue';
import Swiper from'swiper';
import'swiper/swiper-bundle.css';
Vue.use(Swiper);
<template>
<div>
<swiper :options="swiperOptions">
<swiper-slide v - for="(item, index) in imageList" :key="index">
<img :src="item.src" alt="">
</swiper-slide>
</swiper>
</div>
</template>
<script>
import Swiper from'swiper';
import'swiper/swiper - bundle.css';
export default {
data() {
return {
imageList: [],
swiperOptions: {
loop: true,
autoplay: {
delay: 3000
}
}
};
}
};
</script>
- 处理图片数据和交互事件
- 图片数据:
- 可以从后端获取图片数据,例如在
created
钩子函数中使用 axios
发送请求获取图片链接数组。
import axios from 'axios';
export default {
data() {
return {
imageList: []
};
},
created() {
axios.get('/api/getImages').then(response => {
this.imageList = response.data;
});
}
};
- 交互事件:
- Swiper 提供了很多事件,如
slideChange
事件。可以在 swiperOptions
中配置事件处理函数。
export default {
data() {
return {
imageList: [],
swiperOptions: {
loop: true,
autoplay: {
delay: 3000
},
on: {
slideChange() {
console.log('幻灯片切换了');
}
}
}
};
}
};