微信小程序原生組件swiper在mpvue工程中使用注意事項

時下微信小程序開發框架中mpvue是主流的選擇之一。其中,免不了還要使用部分小程序原生的組件。swiper組件幾乎成爲典型小程序界面的必備組成組件之一。但是,我在試用中遇到一個典型問題,很多相關網頁中都沒有給出明確的注意事項總結。在此文中,我主要強調一個值得注意的問題。

把原生組件swiper封裝成一個SFC

爲了突出問題,我給出了最大程度的簡化,把原生組件swiper封裝成一個SFC,文件名爲SimpleSwiper.vue,代碼如下:

<template>
    <swiper :indicator-dots="true" :autoplay="true"
            :interval="5000" :duration="900" :circular="true">
      <div v-for="(item,index) in imgUrls" :key="index">
        <swiper-item>
          <image :src="item" class="slide-image"/>
        </swiper-item>
      </div>
    </swiper>
</template>
<script>
  export default {
    name:"SimpleSwiper",
    props: {
        images: {
          type: Array
      }
    },
    data() {
      return {
        imgUrls: [
          '/static/images/1.png',
          '/static/images/2.jpg'
          ]
      }
    }
}
</script>
<style scoped>
  .slide-image {
    width: 100%;
    height: 100%;
  }
</style>

在mpvue頁面中使用SimpleSwiper組件

爲了說明問題,也是儘量簡化代碼,如下展示的是文件index.vue的內容:

<template>
  <div class="container8">
    <SimpleSwiper/>
  </div>
</template>

<script>
import SimpleSwiper from "@/components/SimpleSwiper"
export default {
  components: {
    SimpleSwiper
  }
}
</script>

<style scoped>
  .container8 {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 200rpx 0;
    box-sizing: border-box;
  }

</style>

顯示失敗

使用上述引用方式使用SimpleSwiper組件,內容得不到任何顯示。更麻煩的是,根本很難判斷是哪裏出了問題。

原因分析

在測試中,我把<div class="container8">這一行直接修改爲<div>,結果一切顯示很好,成功了!
那麼,問題肯定出在樣式的定義裏面。經過初步分析,微信小程序的視圖容器(view,scroll-view和swiper)默認都是dispaly:block方式。經進一步測試發現:小程序flex容器中不能包含block容器——不予顯示。但是,如果把父級容器設置爲block顯示方式,則其中放置swiper沒有問題。即是說,block佈局中可以包含block佈局的子組件。

補充

爲了突出問題,上面代碼使用硬編碼方式,有興趣的朋友可以進一步改進,以便在實際開發中使用之。另外,由於本人沒有對微信小程序顯示模式做詳細分析,故上述結論中可能存在謬誤,歡迎朋友們批評指正。

引用

1,https://www.jianshu.com/p/1fd1f129ee29
2,https://blog.csdn.net/wang_jingj/article/details/82760589
3,https://www.hishop.com.cn/xiaocx/show_58185.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章