时下微信小程序开发框架中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