优化和复用代码

This commit is contained in:
Frankie Huang 2025-04-26 22:50:33 +08:00
parent 700f6980b9
commit 23cadb8da4
2 changed files with 15 additions and 9 deletions

View File

@ -22,7 +22,7 @@
<script setup>
import LeftSidebar from './components/LeftSidebar.vue'
import MainEditor from './components/MainEditor.vue'
import { ref, watch, useTemplateRef, onMounted, onUnmounted } from "vue";
import { ref, watch, useTemplateRef, nextTick, onMounted, onUnmounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { readTextFile, writeTextFile, exists } from '@tauri-apps/plugin-fs';
import { Message } from 'view-ui-plus'
@ -79,7 +79,12 @@ watch(markdownCode, (newMarkdownCode) => {
})
async function readFileContent(filePath) {
try {
mainEditor.value.setMarkdownCode(await readTextFile(filePath));
const fileContent = await readTextFile(filePath);
if (mainEditor.value.isEditorLoadingCompleted()) {
mainEditor.value.setMarkdownCode(fileContent);
} else {
markdownCode.value = fileContent;
}
currentFilePath.value = filePath;
Message.success('已读取文件内容,并加载到编辑器中:' + filePath);
} catch (err) {
@ -97,25 +102,22 @@ async function writeFileContent(markdownCode) {
if (!exist) {
throw new Error(currentFilePath.value + " 文件不存在.");
}
await writeTextFile(currentFilePath.value, markdownCode)
await writeTextFile(currentFilePath.value, markdownCode);
Message.success('文件更新成功:' + currentFilePath.value);
} catch (err) {
Message.error('文件更新失败:' + err);
}
}
onMounted(async () => {
// 使 nextTick
await nextTick();
// splitRight splitTrigger
splitRightWidth.value = window.innerWidth * (1 - split.value) - splitTrigger.value.offsetWidth;
// markdown
window.addEventListener('resize', mainEditor.value.resizeEditorWindow);
//
if (currentFilePath.value.length > 0) {
try {
markdownCode.value = await readTextFile(currentFilePath.value);
Message.success('已读取文件内容,并加载到编辑器中:' + currentFilePath.value);
} catch (err) {
Message.error('文件读取失败:' + err);
}
await readFileContent(currentFilePath.value);
}
mainEditor.value.initMarkdownEditor();
});

View File

@ -65,6 +65,9 @@ const markdownRef = ref(null);
const initMarkdownEditor = () => {
markdownRef.value.initEditor();
}
const isEditorLoadingCompleted = () => {
return markdownRef.value.isEditorLoadingCompleted();
}
const getMarkdownCode = () => {
return markdownRef.value.getMarkdownCode();
}
@ -158,6 +161,7 @@ const resizeEditorWindow = () => {
//
defineExpose({
initMarkdownEditor,
isEditorLoadingCompleted,
getMarkdownCode,
setMarkdownCode,
resizeEditorWindow,