使用的庫是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 = towxmlreturn {app,};
}
這里使用的commonjs
,所以需要安裝@types/node
,并且在tsconfig.json
的types
添加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