四、核心 API 方法
4.1 Vditor 实例方法与使用示例
const vditor = new Vditor('vditor', {
after: () => {
// 设置初始内容
vditor.setValue('# 标题\n\n这是内容');
// 插入内容
vditor.insertValue('## 新章节\n\n这是插入的内容');
// 获取内容
const markdown = vditor.getValue();
console.log(markdown);
// 获取 HTML
const html = vditor.getHTML();
console.log(html);
}
});
// 聚焦和失焦
vditor.focus();
vditor.blur();
// 禁用和启用
vditor.disabled();
vditor.enable();
// 清除缓存
vditor.clearCache();
// 销毁编辑器
vditor.destroy();
4.2 使用 Vue 3 Ref 管理编辑器实例
<template>
<div id="vditor-container"></div>
<button @click="insertImage">插入图片</button>
<button @click="getContent">获取内容</button>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
const editorInstance = ref(null);
const containerId = 'vditor-container';
onMounted(() => {
editorInstance.value = new Vditor(containerId, {
height: 500,
mode: 'ir',
after: () => {
console.log('编辑器已初始化');
}
});
});
const insertImage = () => {
if (editorInstance.value) {
editorInstance.value.insertValue('');
}
};
const getContent = () => {
if (editorInstance.value) {
const content = editorInstance.value.getValue();
console.log('当前内容:', content);
}
};
onBeforeUnmount(() => {
if (editorInstance.value) {
editorInstance.value.destroy();
}
});
</script>
五、事件系统
5.1 事件回调配置
Vditor 提供了丰富的事件回调,用于监听编辑器的各种状态变化。
5.2 事件使用示例
https://yyvgt.cn
const vditor = new Vditor('vditor', {
height: 500,
after: (editor) => {
console.log('编辑器初始化完成', editor);
// 可以在这里获取编辑器实例进行后续操作
},
input: (value) => {
// 实时保存草稿
localStorage.setItem('draft', value);
console.log('内容已更新,长度:', value.length);
},
blur: (value) => {
// 失去焦点时自动保存
saveToBackend(value);
console.log('内容已自动保存');
},
focus: (value) => {
console.log('编辑器已获得焦点');
},
ctrlEnter: (value) => {
// Ctrl+Enter 触发表单提交
submitForm(value);
}
});