uniapp swiper如何根据内容自适应高度
时间: 2023-09-07 20:12:32 浏览: 194
Uniapp Swiper 组件默认高度是固定的,无法根据内容自适应高度。但是可以通过以下两种方式实现:
1. 使用 scroll-view 包裹 swiper,设置 scroll-view 的高度为内容高度
```html
<scroll-view style="height: {{scrollHeight}}px;">
<swiper :style="{height: swiperHeight + 'px'}">
<swiper-item v-for="(item, index) in list" :key="index">
{{item.content}}
</swiper-item>
</swiper>
</scroll-view>
```
```javascript
export default {
data() {
return {
list: [
{ content: '第1页' },
{ content: '第2页' },
{ content: '第3页' },
],
swiperHeight: 0,
scrollHeight: 0,
}
},
mounted() {
this.$nextTick(() => {
uni.createSelectorQuery().in(this).select('.swiper').boundingClientRect(data => {
this.swiperHeight = data.height
uni.createSelectorQuery().in(this).select('.scroll-view').boundingClientRect(data => {
this.scrollHeight = data.height
}).exec()
}).exec()
})
}
}
```
2. 使用自定义组件配合 swiper 实现自适应高度
```html
<!-- my-swiper 组件 -->
<template>
<swiper :style="{height: swiperHeight + 'px'}">
<swiper-item v-for="(item, index) in list" :key="index">
{{item.content}}
</swiper-item>
</swiper>
</template>
<script>
export default {
props: {
list: {
type: Array,
default: () => []
}
},
data() {
return {
swiperHeight: 0,
}
},
mounted() {
this.$nextTick(() => {
uni.createSelectorQuery().in(this).select('.swiper').boundingClientRect(data => {
this.swiperHeight = data.height
this.$emit('swiperHeightChange', data.height)
}).exec()
})
}
}
</script>
<!-- 使用 my-swiper 组件 -->
<template>
<my-swiper :list="list" @swiperHeightChange="swiperHeight = $event"></my-swiper>
</template>
<script>
import MySwiper from './my-swiper'
export default {
components: {
MySwiper,
},
data() {
return {
list: [
{ content: '第1页' },
{ content: '第2页' },
{ content: '第3页' },
],
swiperHeight: 0,
}
},
}
</script>
```
以上两种方式都可以实现 Uniapp Swiper 组件根据内容自适应高度,选择使用哪种方式根据实际情况选择。
阅读全文
相关推荐


















