這個問題,真的,找了好久解決方案,終于解決成功了,
首先問題描述,
本來是用的靜態(tài)數據,swiper渲染沒有問題,
items: [
{url: '111',name:'name1'},
{url: '222',name:'name2'},
{url: '333',name:'name3'},
{url: '444',name:'name4'},
{url: '555',name:'name5'},
{url: '666',name:'name6'},
{url: '777',name:'name7'},
{url: '888',name:'name8'},
{url: '999',name:'name9'},
{url: '000',name:'name10'}
],
后期,動態(tài)獲取數據:
getDeviceList () {
getList({}).then((res) => { // 獲取所有設備
this.items = res.data;
}).catch((err) => {
console.error(err);
});
},
const itemsLength = this.items.length;
for (let i = 0; i < itemsLength; i += 4) { //四畫面輪播
this.pages.push(this.items.slice(i, i + 4));
}
發(fā)現this.pages始終獲取不到this.items的值,swiper渲染不到任何數據,
后來經同事指導,同事說因為數據請求時異步,因此,for循環(huán)應該放在getList方法體中:
getDeviceList () {
getList({}).then((res) => { // 獲取所有設備
this.items = res.data;
const itemsLength = this.items.length;
for (let i = 0; i < itemsLength; i += 4) { //四畫面輪播
this.pages.push(this.items.slice(i, i + 4));
}
).catch((err) => {
console.error(err);
});
},
這樣之后swiper可以渲染數據了,但是我又發(fā)現,畫面不輪播了,并且也拖不動,四處尋找答案,大致分以下兩種方法:
1.在獲取數據之后立即對swiper初始化:
getDeviceList () {
getList({}).then((res) => { // 獲取所有設備
this.items = res.data;
const itemsLength = this.items.length;
for (let i = 0; i < itemsLength; i += 4) { //四畫面輪播
this.pages.push(this.items.slice(i, i + 4));
}
let mySwiper = new Swiper('.swiper-container', {
autoplay: {
delay: 5000, // 5秒切換一次
},
loop: true, //循環(huán)
allowTouchMove: false, // 不允許鼠標拖動
preventClicks: false,//默認true
});
}).catch((err) => {
console.error(err);
});
},
2.在初始化swiper的時候加上以下兩行代碼:
let mySwiper = new Swiper('.swiper-container', {
observer:true,//修改swiper自己或子元素時,自動初始化swiper
observeParents:true,//修改swiper的父元素時,自動初始化swiper
});
親測,第一種方法反正還是不可以滑動,第二種方法可以滑動,但是切換的時候第一條數據不顯示,不知道為什么,
后來參考這個博客完美解決:
https://blog.csdn.net/zhanghuiqi205/article/details/79662586
貼上代碼:
methods: {
carousel () { // swiper
let mySwiper = new Swiper('.swiper-container', {
autoplay: {
delay: 5000, // 5秒切換一次
},
loop: true, //循環(huán)
allowTouchMove: false, // 不允許鼠標拖動
preventClicks: false,//默認true
autoplayDisableOnInteraction: false,
});
//鼠標覆蓋停止自動切換
mySwiper.el.onmouseover = function () {
mySwiper.autoplay.stop();
};
//鼠標移開開始自動切換
mySwiper.el.onmouseout = function () {
mySwiper.autoplay.start();
};
},
getDeviceList () {
let that = this;
getList({}).then((res) => { // 獲取所有設備
this.items = res.data;
const itemsLength = this.items.length;
for (let i = 0; i < itemsLength; i += 4) { //四畫面輪播
this.pages.push(this.items.slice(i, i + 4));
}
that.$nextTick(function () {
that.carousel();
})
}).catch((err) => {
console.error(err);
});
}
}
mounted () {
this.$nextTick(function () {
this.getDeviceList();
this.carousel();
})
}
剛剛接觸vue,對$nextTick()函數還不了解,日后補上。