uniapp 渲染Markdown

  • uniapp 渲染Markdown已关闭评论
  • 113 次浏览
  • A+
所属分类:Web前端
摘要

近日在编写一个小程序,将日记功能移植到小程序中,虽然在手机端写日记一般用不到Markdown,但是仍想在小程序中查看在电脑端写的Markdown格式的内容,如代码块等。

近日在编写一个小程序,将日记功能移植到小程序中,虽然在手机端写日记一般用不到Markdown,但是仍想在小程序中查看在电脑端写的Markdown格式的内容,如代码块等。

经过查询,找到一个被广泛使用的解决方案是towxml

现记录如下:

首先将代码克隆下来

  git clone https://github.com/sbfkcel/towxml.git 

打开根目录的config.js进行自定义的配置

配置完后安装依赖

npm i 

打包

npm run build 

将打包后的dist文件夹复制到uniapp项目的static目录,更名为towxml

在需要使用的页面中使用,主要包括引入towxml组件: import towxml from '../../static/towxml/towxml',引入转换方法:require("@/static/towxml/index.js") 以及最后的使用:

<template> 	<view> 		<view v-if="o" class="reader-title"> 			<view class="date"> 				{{o.date}} 			</view> 			<view class="city"> 				{{o.city}} 			</view> 			<view class="weather"> 				{{o.weather}} 			</view> 		</view> 		 		<towxml :nodes="content"></towxml> 		<!-- <rich-text :nodes="content"></rich-text> --> 		<!-- {{content}} --> 	</view> </template>  <script> import { requestForGetDiaryDetail } from '../../utils/allRequests'; import { decrypt } from '../../utils/crypto'; import towxml from '../../static/towxml/towxml' import marked from 'marked'   	export default { 		components:{ 			towxml:towxml 		}, 		data() { 			return { 				content:'', 				o:null, 				towxmlFun:require("@/static/towxml/index.js") 			}; 		}, 	onLoad(options) { 		requestForGetDiaryDetail(options.id,(a)=>{ 			let c = a.data.result.res[0] 			this.o =c 			let t = decrypt(c.normal) 			// this.content = this.marked(t) 			console.log(this.marked) 			// console.log(this.content) 			this.content = this.towxmlFun(t,'markdown',{ 				// base: 'https://www.xxx.com', 				theme:"light" 			}) 			// console.log(t,this.content) 			 		}) 	} 	} </script>  <style lang="scss"> .reader-title{ 	display: flex; 	justify-content: space-evenly; 	text-align: center; } </style>