npm i md-editor-v3 --save
npm i showdown --save
由于该编辑器输入为markdown
格式,要转换成html
则需要插件转换,因此使用showdown
md-editor-v3
也提供了onHtmlChanged
来转换,不过出于贪图逻辑上的便利没有使用
toolbarsExclude
为toolbar
禁用,去掉不需要的按键
<template>
<MdEditor
toolbarsExclude="['link', 'mermaid', 'katex', 'github', 'save']"
v-model="content"
@onUploadImg="onUploadImg"
>
</MdEditor>
<el-button @click="saveData" type="primary">保存</el-button>
</template>
<script>
import {
ref,
defineComponent,
reactive
} from "vue";
import showdown from "showdown";
import MdEditor from "md-editor-v3";
import "md-editor-v3/lib/style.css";
export default defineComponent({
components: { MdEditor },
setup() {
const state = reactive({
content: ''
});
const onUploadImg = async (
files,
callback
) => {
const res = await Promise.all(
Array.from(files).map((file) => {
return new Promise(async (rev, rej) => {
const form = new FormData();
form.append("files", file);
// 请求图片上传接口 返回网络 url 给 callback
const res = await Api.uploadFile(form);
if (res?.state) {
rev(res.value.url);
}
});
})
);
callback(res.map((item: any) => item));
};
// 点击页面定义的按钮,保存数据,content为markdown文本内容
// 这里没必要使用toolbar的save按键保存文本再点击按钮调用接口
const saveData = async () => {
const { content } = state;
const converter = new showdown.Converter();
const data = {
content: converter.makeHtml(tmContent),
};
const res: any = await Api.addData(data);
if (res?.state) {
ElMessage.success(res?.message ?? "新增成功");
}
}
return {
...toRefs(state),
onUploadImg,
saveData,
};
},
})
</script>