這個(gè)問題,真的,找了好久解決方案,終于解決成功了,
首先問題描述,
本來是用的靜態(tài)數(shù)據(jù),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'}
],
后期,動(dòng)態(tài)獲取數(shù)據(jù):
getDeviceList () {
getList({}).then((res) => { // 獲取所有設(shè)備
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ā)現(xiàn)this.pages始終獲取不到this.items的值,swiper渲染不到任何數(shù)據(jù),
后來經(jīng)同事指導(dǎo),同事說因?yàn)閿?shù)據(jù)請(qǐng)求時(shí)異步,因此,for循環(huán)應(yīng)該放在getList方法體中:
getDeviceList () {
getList({}).then((res) => { // 獲取所有設(shè)備
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可以渲染數(shù)據(jù)了,但是我又發(fā)現(xiàn),畫面不輪播了,并且也拖不動(dòng),四處尋找答案,大致分以下兩種方法:
1.在獲取數(shù)據(jù)之后立即對(duì)swiper初始化:
getDeviceList () {
getList({}).then((res) => { // 獲取所有設(shè)備
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, // 不允許鼠標(biāo)拖動(dòng)
preventClicks: false,//默認(rèn)true
});
}).catch((err) => {
console.error(err);
});
},
2.在初始化swiper的時(shí)候加上以下兩行代碼:
let mySwiper = new Swiper('.swiper-container', {
observer:true,//修改swiper自己或子元素時(shí),自動(dòng)初始化swiper
observeParents:true,//修改swiper的父元素時(shí),自動(dòng)初始化swiper
});
親測(cè),第一種方法反正還是不可以滑動(dòng),第二種方法可以滑動(dòng),但是切換的時(shí)候第一條數(shù)據(jù)不顯示,不知道為什么,
后來參考這個(gè)博客完美解決:
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, // 不允許鼠標(biāo)拖動(dòng)
preventClicks: false,//默認(rèn)true
autoplayDisableOnInteraction: false,
});
//鼠標(biāo)覆蓋停止自動(dòng)切換
mySwiper.el.onmouseover = function () {
mySwiper.autoplay.stop();
};
//鼠標(biāo)移開開始自動(dòng)切換
mySwiper.el.onmouseout = function () {
mySwiper.autoplay.start();
};
},
getDeviceList () {
let that = this;
getList({}).then((res) => { // 獲取所有設(shè)備
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,對(duì)$nextTick()函數(shù)還不了解,日后補(bǔ)上。