---
title: Vue项目中在md-editor-v3工具栏中添加自定义工具
description: 以NEU小站中的“选择课程”工具为例
date: 2025-04-16
# image: helena-hertz-wWZzXlDpMog-unsplash.jpg
categories:
- 奇技淫巧
tags: [
"md-editor-v3",
"Markdown",
"Vue",
"前端",
"NEU小站"
]
lastmod: 2025-04-16T23:56:00+08:00
---
# 效果
在[NEU小站](https://www.东北大学.com/submit)项目(基于Vue3)中,我在md-editor-v3的工具栏中实现了一个“选择课程”工具,可以帮助用户搜索并选择相应的课程,然后插入一个包含课程id的组件标签。效果:
# 实现
- 参考资料:[md-editor-v3 官方 API 文档](https://imzbf.github.io/md-editor-v3/zh-CN/api)
首先我们需要在组件处注册一个自定义工具的模板,注意使用`#defToolbars`,设置好图标、说明文字和点击事件,参考[此处](https://imzbf.github.io/md-editor-v3/zh-CN/api#%F0%9F%A7%B1%20toolbars)。
```html
```
然后,在`data()`的`editorToolbars`中添加自定义工具的配置,这里非常重要,需要用`0`来表示自定义工具的位置。如果有多个自定义工具,则以此类推0、1、2...,类似数组下标。
```js
editorToolbars: [
'bold', 'italic', 'strikethrough', 'title', 'sub', 'sup', 'quote', 'unordered-list',
'ordered-list', 'link', 'image', 'table', 'code-block', 'inline-code', 'preview',
'fullscreen', '-', 'revoke', 'next', '-', 0
],
```
这样我们的自定义图标就会出现在工具栏的对应位置。现在完成`chooseCourse`方法。方法内的逻辑自行定义,但是我们最终的操作一般是需要在编辑器中插入一段文本,所以需要使用编辑器提供的`insert`方法。
参考[insert API](https://imzbf.github.io/md-editor-v3/zh-CN/api#%F0%9F%92%89%20insert),文档如下:
```js
/**
* @params selectedText 选中的内容
*/
editorRef.value?.insert((selectedText) => {
/**
* @return targetValue 待插入内容
* @return select 插入后是否自动选中内容,默认:true
* @return deviationStart 插入后选中内容鼠标开始位置,默认:0
* @return deviationEnd 插入后选中内容鼠标结束位置,默认:0
*/
return {
targetValue: `${selectedText}`,
select: true,
deviationStart: 0,
deviationEnd: 0,
};
});
```
说明我们需要返回一个对象,对象中的`targetValue`就是我们最终插入的内容。这里给个简单的例子:
```js
chooseCourse() {
const id = 3;
this.$refs.markdownEditor?.insert((selectedText) => {
return {
targetValue: `\n`
}
})
}
```
这样,点击这个工具,就会在编辑器中插入``。具体的查询逻辑可以自行实现,这里不再赘述。