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;

	}

大功告成

相关推荐
晴天16几秒前
HarmonyOS 和 React 对比-Day22
前端·华为·harmonyos
海鸥两三3 分钟前
【websocket合集2】websocket.js源码解析和页面调用示例
javascript·websocket·网络协议
AlienZHOU7 小时前
DeepSeek Harness 插件:HTML 实时可视化编辑
前端·agent·deepseek
剪刀石头布啊9 小时前
javascript手动实现继承
前端
Elias不吃糖9 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
vipbic10 小时前
一个前端的 9 天重构:我是怎么用 Codex 重做航栈的
前端·javascript·后端
Eason_Lou11 小时前
【无标题】
前端·vue.js·html
_codemonster12 小时前
npm run dev 是在开发模式运行,怎么在生产环境运行
前端·npm·node.js
kyriewen12 小时前
我受够了复制报错去问 AI,花一下午给控制台做了个调试助手
前端·javascript·ai编程