因为vue中更新 DOM 时是异步执行的,
data() {
return {
imgArray: [] //轮播图片
}
},
created() {
this.getImgArray()
},
mounted() {
new Swiper('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination'
},
autoplay: true
})
},
methods: {
//获取轮播图片
async getImgArray() {
const res = await this.$http.get('/api/homecasual')
console.log(res)
this.imgArray = res.data.message.data
}
},
上面代码就是你在获取完数据之前,就已经实例化完成了,所以在等你渲染完dom,不会再实例化一遍了,所以这时候就需要用到nextTick这个函数了,这个方法通俗来说
$nextTick 通俗讲,页面渲染完成后才会调用的方法
所以我们要把上面的方法做一下改进,
data() {
return {
imgArray: [] //轮播图片
}
},
created() {
this.getImgArray()
},
mounted() {},
methods: {
//获取轮播图片
async getImgArray() {
const res = await this.$http.get('/api/homecasual')
console.log(res)
this.imgArray = res.data.message.data
}
},
watch: {
//监听轮播数据变化后再创建实例
imgArray() {
this.$nextTick(() => {
new Swiper('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination'
},
autoplay: true
})
})
}
}
在watch上监听一下,如果imgArray发生了变化,我们再让他创建实例即可解决