如何在项目中使用 Markdown 编辑器
为什么用 Markdown?
一套通用的文本编辑语法,可以在各大网站上统一标准、渲染出统一的样式,比较简单易学。
推荐的 Md 编辑器:https://github.com/bytedance/bytemd
阅读官方文档,下载编辑器主体、以及 gfm(表格支持)插件、highlight 代码高亮插件
新建 MdEditor 组件,编写代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <Editor :value="value" :plugins="plugins" @change="handleChange" /> </template> <script setup lang="ts"> import gfm from "@bytemd/plugin-gfm"; import highlight from "@bytemd/plugin-highlight"; import { Editor, Viewer } from "@bytemd/vue-next"; import { ref } from "vue"; const plugins = [ gfm(), highlight(), // Add more plugins here ]; const value = ref(""); const handleChange = (v: string) => { value.value = v; }; </script> <style scoped></style>
|
隐藏编辑器中不需要的操作图标(比如 GitHub 图标):
1 2 3
| .bytemd-toolbar-icon.bytemd-tippy.bytemd-tippy-right:last-child { display: none; }
|
MdEditor 示例代码:
要把 MdEditor 当前输入的值暴露给父组件,便于父组件去使用,同时也是提高组件的通用性,需要定义属性,把 value 和 handleChange 事件交给父组件去管理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| /** * 定义组件属性类型 */ interface Props { value: string; handleChange: (v: string) => void; } /** * 给组件指定初始值 */ const props = withDefaults(defineProps<Props>(), { value: () => "", handleChange: (v: string) => { console.log(v); }, });
|