feat: init commit
This commit is contained in:
95
src/components/MarkdownEditor.vue
Normal file
95
src/components/MarkdownEditor.vue
Normal file
@@ -0,0 +1,95 @@
|
||||
<template>
|
||||
<div ref="vditorRef" class="vditor"></div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, defineExpose } from 'vue';
|
||||
import Vditor from 'vditor';
|
||||
import 'vditor/dist/index.css';
|
||||
import { userInfoStore } from '@/store/store';
|
||||
|
||||
const userInfo = userInfoStore();
|
||||
|
||||
|
||||
const vditorRef = ref(null);
|
||||
let vditor = null;
|
||||
|
||||
// 定义 localStorage 的 key
|
||||
const STORAGE_KEY = 'publishArticle';
|
||||
|
||||
defineExpose({
|
||||
getContent,
|
||||
setContent,
|
||||
clearContent,
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
vditor = new Vditor(vditorRef.value, {
|
||||
height: 400,
|
||||
toolbar: [
|
||||
'headings', 'bold', 'italic', 'strike', '|',
|
||||
'list', 'ordered-list', 'check', '|',
|
||||
'quote', 'line', 'code', 'inline-code', '|',
|
||||
'upload', 'link', 'table', '|',
|
||||
'preview', 'fullscreen'
|
||||
],
|
||||
placeholder: '请输入你的文章内容...',
|
||||
mode: 'sv',
|
||||
cache: {
|
||||
enable: false, // 禁用vditor内置缓存
|
||||
},
|
||||
upload: {
|
||||
url: '/api/admin/upload/img',
|
||||
headers: {
|
||||
Authorization: `Bearer ${userInfo.token}`
|
||||
},
|
||||
fieldName: 'image',
|
||||
success(_, response) {
|
||||
response = JSON.parse(response);
|
||||
console.log(response);
|
||||
if (response.code === 200) {
|
||||
console.log('上传成功');
|
||||
vditor.insertValue('')
|
||||
}
|
||||
}
|
||||
},
|
||||
after() {
|
||||
console.log('Vditor 初始化完成');
|
||||
// 初始化后,加载本地缓存内容
|
||||
const cachedContent = localStorage.getItem(STORAGE_KEY);
|
||||
if (cachedContent) {
|
||||
vditor.setValue(cachedContent);
|
||||
}
|
||||
|
||||
},
|
||||
// 监听输入变化,实时保存
|
||||
input(value) {
|
||||
localStorage.setItem(STORAGE_KEY, value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 获取内容
|
||||
function getContent() {
|
||||
return vditor.getValue();
|
||||
}
|
||||
|
||||
// 设置内容
|
||||
|
||||
function setContent(markdown) {
|
||||
vditor.setValue(markdown);
|
||||
localStorage.setItem(STORAGE_KEY, markdown);
|
||||
}
|
||||
|
||||
// 清空内容(比如发布成功后)
|
||||
function clearContent() {
|
||||
vditor.setValue('');
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.vditor {
|
||||
border: 1px solid #ccc;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user