uni-app开发微信小程序,如何使用towxml去渲染md格式和html标签格式的内容?

uni-app开发微信小程序,如何使用towxml去渲染md格式和html标签格式的内容?

前言

一次偶然的面试,面试官问到,你有没有用过towxml?

我:没有。

于是面试结束后,就开始在百度查了,查到了它的githup地址towxml地址,然后就把代码拉下来,好好扒开看看。

最终做出了一个来渲染面试题答案的组件,实现了一个刷面试题的小程序。

先看效果

下面这个截图是从蝌蚪智汇 小程序里面截出来的,有兴趣的可以去看看

如何在项目中使用towxml

第一步

先在项目的根目录创建一个wxcomponents的文件夹,然后把towxml的源码放进去,如下图所示

第二步

直接引入towxml方法使用,完整代码如下:

javascript 复制代码
<template>
	<view class="md-view">
		<!-- 页面头部 -->
		<cu-custom bgColor="bg-gradual-pink" :isBack="true" :isCustomBackFn="true">
			<block slot="backText">返回</block>
			<block slot="content">md文档展示</block>
		</cu-custom>
		<towxml :nodes="html" />
	</view>
</template>

<script>
	import towxml from "@/wxcomponents/towxml/index.js";
	import { text, htmlText } from './md-text.js';
	
	export default {
		name: 'md-view',
		data(){
			return {
				html: ''
			}
		},
		mounted() {
			// 还可以直接渲染html代码towxml(htmlText, 'html')
			this.html = towxml(text, 'markdown')
			console.log(this.html);
		}
	}
</script>

<style lang="scss" scoped>
</style>

md-text.js文件代码:

javascript 复制代码
export const text = `

## 渲染 code 方法, 如下

\`\`\`html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>

<body>
  
</body>
</html>

<script>

</script>

\`\`\`
`

export const htmlText =
	"<p style=\"line-height: 2;\"><span style=\"font-family: Pacifico;\">当一个Vue实例创建时,Vue会遍历</span><strong style=\"font-family: Pacifico;\">data</strong><span style=\"font-family: Pacifico;\">中的属性,用 </span><strong style=\"font-family: Pacifico;\">Object.defineProperty</strong><span style=\"font-family: Pacifico;\">(vue3.0使用proxy )将它们转为 </span><strong style=\"font-family: Pacifico;\">getter/setter</strong><span style=\"font-family: Pacifico;\">,并且在内部追踪相关依赖,在属性被访问和修改时通知变化。 每个组件实例都有相应的 </span><strong style=\"font-family: Pacifico;\">watcher </strong><span style=\"font-family: Pacifico;\">程序实例,它会在组件渲染的过程中把属性记录为依赖,之后当依赖项的setter被调用时,会通知watcher重新计算,从而致使它关联的组件得以更新。</span></p>"

总结

towxml使用起来倒是不难,但有的效果展示还是不太理想,可以去改改源码达到你想要的效果哦

关注我不迷路

不定期发表前端开发技巧类的文章

相关推荐
Frag0ut4 分钟前
Notepad++ 零基础入门:从记事本到代码编辑器的平滑过渡(2026最新版)
python·编辑器·html·json·notepad++·markdown·记事本
云-缩影1 小时前
拆解微信小程序后端架构:ECS、RDS、SSL 和 VPC 怎么配合
微信小程序·架构·ssl
用户298698530141 小时前
Python 实现 HTML 转纯文本:两种场景下的文档模型方案
python·html·api
拖孩2 小时前
AI 帮我写的小程序上线 44 天:36 个人进了收银台,8 个人付钱
前端·后端·微信小程序
前端架构师-老李3 小时前
HTML与CSS基础第七课—HTML 中的a标签(跳转链接)
前端·css·html
sinat_2676119112 小时前
用 AI 开发微信小程序(八):一个极简收纳工具的开发复盘
微信小程序·小程序
PedroQue9920 小时前
0.8.2 新增 backFallback 配置,无 tabbar 页返回无忧
前端·uni-app
李纲明1 天前
微信小程序真机预览白屏或 request 失败:先核 request 合法域名与 TLS,再查体验版与本地缓存
缓存·微信小程序·小程序·小程序开发·devdiy·真机预览·合法域名
PedroQue991 天前
v0.2.0 架构升级:class + reactive 重塑状态管理
前端·uni-app