npm i swiper
import Swiper from "swiper";
import "swiper/css/swiper.css";
**-----1.由于swiper组件必须在界面加载完毕后在才能使用,所以实例应该放在mounted函数里
**-----2.由于getItems函数是异步请求数据,所以要处理swiper实例在数据请求成功后创建,
使用 this.$nextTick([callback]),nextTick即页面加载完之后执行回调函数,方法有3个:
**-----2.1直接利用async和await
async mounted() {
await this.$store.dispatch("getItems");
this.$nextTick(() => {
var mySwiper = new Swiper(".swiper-container", {
loop: true,
pagination: {
el: ".swiper-pagination"
}
});
});
}
**-----2.2在getItems函数中传一个参数cb,函数最后添加一句代码typeof cb==='function' &&cb()
在dispatch getItems的时候传递回调函数
async getItems({ commit },cb) {
const result = await reqItems()
if (result.code === 0) {
const items = result.data
commit(RECEIVE_ITEMS, items)
typeof cb==='function' &&cb()
}
},
mounted() {
this.$store.dispatch("getItems", () => {
this.$nextTick(() => {
var mySwiper = new Swiper(".swiper-container", {
loop: true,
pagination: {
el: ".swiper-pagination"
}
});
});
});
}
**-----2.3在watch中监视执行
watch: {
items() {
this.nextTick(() => {
var mySwiper = new Swiper(".swiper-container", {
loop: true,
pagination: {
el: ".swiper-pagination"
}
});
});
}
}