vue swiper 修改配置 数据更新 父组件向子组件myswiper传递多次参数 子组件只显示第一次传递的数据 解决方法

问题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;
    },
  },

页面效果:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值