時下微信小程序開發框架中mpvue是主流的選擇之一。其中,免不了還要使用部分小程序原生的組件。swiper組件幾乎成爲典型小程序界面的必備組成組件之一。可是,我在試用中遇到一個典型問題,不少相關網頁中都沒有給出明確的注意事項總結。在此文中,我主要強調一個值得注意的問題。html
爲了突出問題,我給出了最大程度的簡化,把原生組件swiper封裝成一個SFC,文件名爲SimpleSwiper.vue,代碼以下: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>
爲了說明問題,也是儘可能簡化代碼,以下展現的是文件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.htmlide