您的位置:首页 > Web前端 > Vue.js

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

2018-12-19 22:24 423 查看

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息