uniapp自定义富文本现实组件(支持查看和收起)

废话不多说上代码

CollapseText.vue

javascript 复制代码
<template>
	<view v-if="descr">
		<scroll-view class="collapse-text" :style="{maxHeight: computedMaxHeight}">
			<!-- <slot></slot> -->
			<rich-text :nodes="descr"></rich-text>
		</scroll-view>
		<view class="lookcount" @click="handleViewAll">
			{{operateText}}
			<image v-if="show" src="../../static/sq@2x.png" mode=""></image>
			<image v-else src="../../static/zk@2x.png" mode=""></image>
		</view>
	</view>
</template>

<script>
	export default {
		name: "CollapseText",
		props: {
			maxHeight: {
				default: 230
			},
			descr: ''
		},
		data() {
			return {
				overflow: false,
				show: false,
				operateText: '查看全部'
			};
		},
		computed: {
			computedMaxHeight() {
				return (!this.maxHeight || this.show || !this.overflow) ? null : this.maxHeight + 'rpx'
			}
		},
		mounted() {
			const query = uni.createSelectorQuery().in(this);
			query.select('.collapse-text').fields({
				rect: true,
				scrollOffset: true,
				size: true
			}, data => {
				this.overflow = data.height <= data.scrollHeight
			}).exec();

		},
		methods: {
			handleViewAll() {
				this.show = !this.show
				this.operateText = this.show ? '收起' : '查看全部'
			}
		}
	}
</script>

<style>
	.collapse-text {
		overflow: hidden;
	}

	.lookcount {
		height: 88rpx;
		font-size: 24rpx;
		color: #646464;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.lookcount image {
		width: 32rpx;
		height: 32rpx;
		margin-left: 4rpx;
	}
</style>

用法

首先导入

剩下就是直接在用template了

最后样式补上

这里方便复制

javascript 复制代码
.navcount {
		width: 686rpx;
		font-size: 28rpx;
		color: #646464;
		line-height: 40rpx;
		max-height: 300rpx;
		overflow: hidden;

	}

大功告成

相关推荐
web守墓人1 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
为风而战1 小时前
uni-app X APP在线升级 解决【uni-upgrade-center-app】未配置uni-upgrade-center 问题
uni-app
Savior`L1 小时前
CSS知识复习5
前端·css
许白掰1 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
雪碧聊技术5 小时前
uniapp如何创建并使用组件?组件通过Props如何进行数据传递?
uni-app·创建组件·使用组件·props数据传递
中微子5 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
@Dream_Chaser5 小时前
uniapp页面间通信
uni-app
秋田君6 小时前
深入理解JavaScript设计模式之命令模式
javascript·设计模式·命令模式
中微子6 小时前
React 状态管理 源码深度解析
前端·react.js
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript