优化和复用代码

This commit is contained in:
Frankie Huang 2025-04-26 22:43:36 +08:00
parent 700f6980b9
commit e6c008f388
2 changed files with 14 additions and 8 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) {
@ -104,18 +109,15 @@ async function writeFileContent(markdownCode) {
}
}
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 = () => {
markdownRef.value.isEditorLoadingCompleted();
}
const getMarkdownCode = () => {
return markdownRef.value.getMarkdownCode();
}
@ -158,6 +161,7 @@ const resizeEditorWindow = () => {
// 对父组件暴露数据或方法
defineExpose({
initMarkdownEditor,
isEditorLoadingCompleted,
getMarkdownCode,
setMarkdownCode,
resizeEditorWindow,