问题1:vue-awesome-swiper初始化swiperOption后,如何修改options中的配置,例如slidesPerView、autoplay等信息?
解决方案:修改轮播图的params属性
<swiper ref="mySwiper" id="my-swiper" :options="options">
<!-- ...... -->
</swiper>
computed: {
mySwiper() {
return this.$refs.mySwiper.$swiper;
},
},
mounted() {
let newV = 3;
this.mySwiper.params.slidesPerView = newV;
}
api参考链接:中文api - Swiper中文网
问题2:父组件向子组件传递多次参数,子组件只显示第一次传递的结果,子组件只接收第一次?
结论:子组件其实都接收到了,可以监听props的值来更新组件的值。
props: {
options: {
type: Object,
default() {
return {};
},
},
},
computed: {
optionsWatch() {
return this.options?.slidesPerView;
},
},
watch: {
optionsWatch(newV, oldV) {
console.log(newV, oldV);
// 更新你需要更新的组件的值
this.mySwiper.params.slidesPerView = newV;
},
},
最后来说说我遇到的问题:我想要实现轮播图动态更新slidesPerView,当轮播内容大于4,slidesPerView为4,否则轮播内容有多少,slidesPerView为多少,即
slidesPerView: that.curProduct.length <= 4 ? that.curProduct.length : 4
但是curProduct这个值的是要通过异步请求返回的,一开始curProduct为空,即slidesPerView初值为0,传递给自己封装的轮播图组件后就,轮播图只显示第一次传递参数的结果
data() {
return {
curProduct: [],
}
},
methods: {
setOptions4() {
let that = this;
let options4 = {
slidesPerView: that.curProduct.length <= 4 ? that.curProduct.length : 4,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
};
return options4;
},
getProductInActivity() {
getProductInActivity().then((res) => {
this.curProduct = res.data;
});
},
},
我最终的解决方案:监听子组件接受到的参数,当监听到参数发生改变,就更新slidesPerView的值。
props: {
options: {
type: Object,
default() {
return {};
},
},
},
computed: {
optionsWatch() {
return this.options?.slidesPerView;
},
mySwiper() {
return this.$refs.mySwiper.$swiper;
},
},
watch: {
optionsWatch(newV, oldV) {
console.log(newV, oldV);
this.mySwiper.params.slidesPerView = newV;
},
},
页面效果: