欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > uniapp 自定义展开/收起组件(适配H5、微信小程序等)

uniapp 自定义展开/收起组件(适配H5、微信小程序等)

2025/3/31 16:35:09 来源:https://blog.csdn.net/Binglianxiaojiao/article/details/146520631  浏览:    关键词:uniapp 自定义展开/收起组件(适配H5、微信小程序等)

今天遇到啦个需求,内容展开收起功能,没有的用,那边手搓一个吧

因为项目使用到的也只有H5端和微信小程序端,所以如果其余端开发的话,需要看一下适当的调整,不出意外的话就直接用吧,废话不多说,上菜:

<template><view class="more"><view class="more_content" :style="{ maxHeight: getMaxH }"><view class="more_content_text" :style="{ fontSize: size + 'rpx' }"><slot>{{ text }}</slot></view></view><view class="more_btn" :style="{ fontSize: size + 'rpx' }" v-if="domHeight.inner > domHeight.outer"@tap="isMore = !isMore">{{ isMore ? '收起' : '展开' }}</view></view>
</template><script>
export default {/*** 1、设置maxH,row将会失效*/props: {// 文本text: {type: String,default: ''},// 最大高度 rpxmaxH: {type: Number,default: 0},// 字体大小 rpxsize: {type: Number,default: 28},// 行数row: {type: Number,default: 2}},data() {return {isMore: false, // 是否显示更多domHeight: {outer: 0,inner: 0,}}},async mounted() {let outerDom = await this.$util.getDomInfo('.more_content', this);let innerDom = await this.$util.getDomInfo('.more_content_text', this);this.domHeight = {outer: outerDom.height,inner: innerDom.height}},computed: {getMaxH() {let h = this.row * this.size * 1.5;// #ifdef MP-WEIXINh -= 8;// #endiflet more = this.domHeight.inner / (uni.upx2px(100) / 100) + 'rpx'; // 展开高度let noMore = this.maxH ? (this.maxH + 'rpx') : (h + 'rpx'); // 收起高度return this.isMore ? more : noMore},}
}
</script><style lang="scss" scoped>
.more {position: relative;.more_btn {position: absolute;right: 0;bottom: 0;padding-left: 20rpx;line-height: 1.5;// background: red;background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 20%, rgba(255, 255, 255, 1) 100%);}
}.more_content {overflow: hidden;transition: .2s;
}.more_content_text {word-wrap: break-word;word-break: break-all;white-space: pre-wrap;line-height: 1.5;
}
</style>
参数说明
props说明默认值
text需要显示的文本-
maxH设置最大高度(设置maxH后row属性便会失效)0
size内容字体大小(行高为1.5倍)28
row收起时显示行数(设置maxH后row属性便会失效)2
插槽
default默认插槽-

可通过text属性传入文本,也可以通过默认插槽传入自定义内容,任君选择~

补充一下组件里面使用到的工具函数:

this.$util.getDomInfo

	getDomInfo: function (id, that) {return new Promise((resolve, reject) => {if (!id) return reject('id/类名 不能为空')if (!that) return reject('this指向不能为空')const query = uni.createSelectorQuery().in(that);query.select(id).boundingClientRect(data => {// console.log("节点离页面顶部的距离为" + data.height);resolve(data || {})}).exec();})},

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词