[踩坑笔记]uniapp vue3版本使用toxml渲染markdown

924 阅读1分钟

第一步 下载源码并构建

github.com/sbfkcel/tow…拉取代码,并且npm run build获取构建文件,改名为toxml

git clone https://github.com/sbfkcel/towxml.git
npm run build

第二步 修改 towxml/decode.json,将所有路径修改

"usingComponents": {
    "decode": "./decode",
    "audio-player": "./audio-player/audio-player",
    "echarts": "./echarts/echarts",
    "latex": "./latex/latex",
    "table": "./table/table",
    "todogroup": "./todogroup/todogroup",
    "yuml": "./yuml/yuml",
    "img": "./img/img"
}

第三步 在page.json中添加配置引入组件

"usingComponents":{
    "towxml": "/wxcomponents/Towxml/towxml"
 }

第四步 在main.ts中引入用于解析md的API

// 这里有个点, 之前使用的是./wxcomponents,一直报错,将.去掉就没问题了,但是不明白原因
const towxml = require('/wxcomponents/Towxml/index');
export function createApp() {
  const app = createSSRApp(App)
  app.config.globalProperties.$towxml = towxml
  return {
    app
  }
}

第五步 在页面中直接使用

<template>
  <div>
    <towxml :nodes="parseMd(str)" />
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, computed } from "vue";

const str = ref("### 一级标题")
let { appContext } = getCurrentInstance() as any;
const parseMd = computed(() => (str: string) => {
  // 这里可能str为undefined, 所以需要判断一下,感觉可能uniapp模板部分获取的值有延迟
  if (str) {
    return appContext.config.globalProperties.$towxml(str, "markdown");
  }
  return "";
});
</script>