vue3 使用 md-editor-v3(MdEditor)富文本插件

本文介绍了如何在Vue3项目中集成并使用md-editor-v3富文本编辑器,包括安装、基本用法、工具栏定制以及XSS防护。通过示例代码展示了排除特定工具栏项、监听图片上传和保存事件等功能,并提醒了使用`sanitize`可能导致的代码高亮问题。同时,提供了完整代码示例和注意事项,帮助开发者实现富文本内容的分享和存储。
摘要由CSDN通过智能技术生成

vue3 使用 md-editor-v3(MdEditor)富文本插件

官方文档: https://imzbf.github.io/md-editor-v3/docs/index

安装方式

  • yarn
    yarn add md-editor-v3

  • npm
    npm install md-editor-v3

使用

toolbarsExclude 选择不需要展示的工具栏
// template
<MdEditor
    toolbarsExclude="['link', 'mermaid', 'katex', 'github']"
    v-model="text"
    @onUploadImg="onUploadImg"
    @onSave="codeSave"
>
</MdEditor>
toolbarsExclude 的属性
'bold',
  'underline',
  'italic',
  '-',
  'strikeThrough',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'mermaid',
  'katex',
  '-',
  'revoke',
  'next',
  'save',
  '=',
  'pageFullscreen',
  'fullscreen',
  'preview',
  'htmlPreview',
  'catalog',
  'github';

// 对应功能名称
'加粗',
  '下划线',
  '斜体',
  '删除线',
  '下标',
  '上标',
  '引用',
  '无序列表',
  '有序列表',
  '行内代码',
  '块级代码',
  '链接',
  '图片',
  '表格',
  '图表',
  '公式',
  '后退一步',
  '前进一步',
  '保存',
  '页面内全屏',
  '屏幕全屏',
  '内容预览',
  'html代码预览',
  '目录',
  '源码地址';

// script 引入
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
可以引入 sanitizeHtml 进行 xss 防范
// 安装
// yarn add sanitize-html
// npm install sanitize-html


<template>
  <MdEditor :sanitize="sanitize" />;
</template>

import sanitizeHtml from 'sanitize-html';

但是不知道是我使用的原因还是因为版本自身的bug 我使用 :sanitize="sanitize" 导致代码不高亮,具体的你们可以自己试试

效果图

RUNOOB 图标

完整代码
<template>
    <div class="codeShare">
        <div>
            <el-alert
                style="margin: 10px 0"
                title="信息"
                type="warning"
                description="我们不会公开你的代码,代码分享后将会给你一个访问链接,链接有效期为三天。在刷新页面前请保存好你的链接"
                show-icon
            ></el-alert>
            <el-progress v-show="isDis" :percentage="load" />
            <!-- 只读模式 :previewOnly="true" -->
            <!-- :sanitize="sanitize" 使用会导致代码不高亮 -->
            <el-button style="margin-bottom: 10px;" @click="shareCode">分享</el-button>
            <MdEditor
                toolbarsExclude="['link', 'mermaid', 'katex', 'github']"
                v-model="text"
                @onUploadImg="onUploadImg"
                @onSave="codeSave"
            >
            </MdEditor>
        </div>
    </div>
</template>

<script lang="ts">
import { shareCodeApi, onUploadImg } from '../util/api'
import {defineComponent, reactive, toRefs, onMounted} from 'vue'

import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
// 使用 sanitizeHtml 处理不安全的 html
import sanitizeHtml from 'sanitize-html';
import { ElMessage, ElMessageBox  } from 'element-plus';

interface shareData {
    text: string,
    load: number,
    isDis: boolean
}

export default defineComponent({
    name: "codeShare",
    components: {MdEditor},
    setup() {
        const data = <shareData> reactive({
            text: '',
            load: 0,
            isDis: false
        })

        const codeSave = (v: string):void => {
            ElMessage.info('已保存')
            localStorage.setItem('codeSave', v)
        }

        const sanitize = (html: string): string => {
            console.log(sanitizeHtml(html))
            return sanitizeHtml(html)
        }

        const href = window.location.href;
        const url = href.substring(0, href.length - 10);

        // 分享代码
        const shareCode = () => {
            if(data.text === '') {
                return ElMessage.error('为空不能分享!!!')
            }
            // @ts-ignore
            shareCodeApi({text: data.text}).then( (res) => {
                if(res.data.code === 200) {
                    ElMessageBox.alert(`你的访问链接为:<br /><a style="word-break:break-all;" target='_blank' href="${url}/getCodeShare/${res.data.data}">${url}/getCodeShare/${res.data.data}</a>`, '提示', {
                        confirmButtonText: 'OK',
                        dangerouslyUseHTMLString: true,
                    })
                    localStorage.removeItem('codeSave')
                }
            })
        }

        onMounted(() => {
            if(localStorage.getItem('codeSave')) {
                data.text = localStorage.getItem('codeSave') || ''
            }
        })

        return {
            ...toRefs(data),
            codeSave,
            sanitize, shareCode
        }
    },
    methods: {
        // 图片上传
        async onUploadImg(files: FileList, callback: (urls: string[]) => void) {
            this.load = 0
            this.isDis = true
            const res = await Promise.all(
                Array.from(files).map((file) => {
                    return new Promise((rev, rej) => {
                        const form = new FormData();
                        form.append('img', file);
                        // @ts-ignore
                        onUploadImg(form, this.onUploadProgress).then((res) => {
                            rev(res)
                        })
                    });
                })
            );

            callback(res.map((item: any) => item.data.data));
        },
        // 获取图片上传进度
        onUploadProgress(e: number) {
            this.load = e
            if(e === 100) {
                setTimeout(() => {
                    this.isDis = false
                },1000)
            }
        },


    }
});
</script>

<style scoped>
/deep/ .md {
    height: 600px!important;
}
</style>

图片上传的接口和发布富文本的接口需要自己编写,我这边是封装了后端的接口,这边你自己封装一个就可以实现上传图片还发布了。有需要也可以私信问我。提供的代码只是一个逻辑,有很多引用的代码没有提供。

  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
Vue 3 中按需引入 v-md-editor 编辑器,你可以按照以下步骤进行操作: 1. 首先,安装 v-md-editor 包及其相关依赖: ``` npm install v-md-editor @kangc/v-md-editor @kangc/v-md-editor/lib/theme/style/vuepress.css ``` 2. 在你的 Vue 3 项目中,创建一个名为 `vmdeditor.js` 的文件,用于配置按需引入: ```javascript // vmdeditor.js import { createApp } from 'vue' import VMdEditor from '@kangc/v-md-editor' import '@kangc/v-md-editor/lib/style/base-editor.css' import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js' // 引入你需要使用的编辑器组件 import { Vditor, CodeMirror, Prism, TextArea } from '@kangc/v-md-editor/lib/codemirror-editor' // 注册编辑器组件 VMdEditor.use(vuepressTheme, { Prism, CodeMirror, TextArea }) // 创建 Vue 应用实例 const app = createApp({}) app.use(VMdEditor) app.mount('#app') ``` 3. 在你的 Vue 3 项目中的入口文件(通常是 `main.js`)中引入 `vmdeditor.js` 文件: ```javascript // main.js import { createApp } from 'vue' import App from './App.vue' import './vmdeditor.js' // 引入 vmdeditor.js 文件 createApp(App).mount('#app') ``` 4. 现在,你可以在 Vue 组件中使用 v-md-editor 编辑器组件了。例如,在 `App.vue` 组件中使用 Vditor 编辑器: ```vue <template> <v-md-editor> <Vditor v-model="content" /> </v-md-editor> </template> <script> export default { data() { return { content: '' } } } </script> ``` 通过以上步骤,你可以按需引入 v-md-editor 编辑器,并在 Vue 3 项目中使用。记得根据你的需求选择合适的编辑器组件进行引入和使用
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又蓝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值