uniapp+vue3嵌入Markdown格式

566 阅读1分钟

如果您觉得这篇文章有帮助的话!给个点赞和评论支持下吧,感谢~

作者:前端小王hs

阿里云社区博客专家/清华大学出版社签约作者/csdn百万访问前端博主/B站千粉前端up主

使用的库是towxml

第一步:下载源文件,那么可以git clone,也可以直接下载压缩包 git clone https://github.com/sbfkcel/towxml.git

第二步:设置文件夹内的config.js,可以选择自己需要的格式

第三步:安装依赖和打包 npm i npm run build 打包完成后会生成一个dist文件夹,改名字为towxml

第四步:在uniapp项目的src目录下新建wxcomponents目录(需要注意的是这个文件名是有要求的),然后将towxml放到wxcomponents

第五步:修改towxml里的decode.json,将里面的前缀改为相对路径./

"decode": "/towxml/decode",
改为
"decode": "./decode",

第六步:在全局挂载towxml,代码如下:

const towxml = require('./wxcomponents/towxml/index');
export function createApp() {
  const app = createSSRApp(App);
  app.config.globalProperties.$towxml = towxml
  return {
    app,
  };
}

这里使用的commonjs,所以需要安装@types/node,并且在tsconfig.jsontypes添加node,代码如下:

"types": ["@dcloudio/types","nutui-uniapp/global.d.ts","node"]

第七步:在pages.json里需要的页面的style属性里使用组件

		{
			"path": "pages/question_detail/index",
			"style": {
				"navigationBarTitleText": "面试题",
				"usingComponents": {
					"towxml": "/wxcomponents/towxml/towxml"
				}
			}
		},

第八步:在页面使用towxml

<towxml :nodes="testData" class="towxml-content" />
import { reactive, ref, getCurrentInstance } from 'vue';

const instance = getCurrentInstance();
const appContext = instance?.appContext
const testData = appContext?.config.globalProperties.$towxml('``111``', 'markdown')

第九步:由于该组件默认带有边距,所以需要在towxml/style/main.scss里进行手动修改,代码如下:

// towxml/style/main.scss
.h2w__main {
    margin: 0;
    padding-top: 0;
}

在组件里使用class! important是无效的

实现效果: 在这里插入图片描述

参考了知乎文章:uniapp中解析markdown支持网页和小程序

参考了CSDN文章:uni-app中使用towxml