Vue3和Electron实现桌面端应用详解

为了方便记录一些个人随笔,我最近用Laravel和Vue 3.0撸了一个博客系统,其中使用到了一个基于markdown-it 的 markdown 编辑器Vue组件v-md-editor。我感觉用它去编写markdown还是很方便的。后面就有了一个想法,基于此组件用Electron来实现一个markdown桌面端应用,自己平时拿来使用也是个不错的选择。

题外话:VS Code就是用Electron开发出来的桌面应用,我现在除了移动端的开发外,其他的都是使用VS Code来开发了,各种插件开发起来真的很方便。

接下来我就带大家来一步步来实现这个功能。

Vue CLI 搭建Vue项目

在选择的目录下执行vue create electron-vue3-mark-down

选择自定义的模板(可以选择默认的Vue 3 模板)

Vue3和Electron实现桌面端应用详解

选择Vue3TypeScript, 其他的选项基于自身项目决定是否选择

vue3 + TypeScript

执行npm run serve看看效果

效果

Vue项目改造为markdown编辑器

执行npm i @kangc/v-md-editor@next -S安装v-md-editor

添加TypeScript类型定义文件

由于v-md-editor这个库没有TypeScript类型定义文件,我就直接在shims-vue.d.ts这个文件的后面添加的,当然也可以新建一个文件添加申明(tsconfig.json能找到这个文件就OK)。

declare module "*.vue" { import type { DefineComponent } from "vue"; const component: DefineComponent<{}, {}, any>; export default component; } <!-- 添加的内容 --> declare module "@kangc/v-md-editor/lib/theme/vuepress.js"; declare module "@kangc/v-md-editor/lib/plugins/copy-code/index"; declare module "@kangc/v-md-editor/lib/plugins/line-number/index"; declare module "@kangc/v-md-editor"; declare module "prismjs";

改造App.vue

<template> <div> <v-md-editor v-model="content"></v-md-editor> </div> </template> <script lang="ts"> // 编辑器 import VMdEditor from "@kangc/v-md-editor"; import "@kangc/v-md-editor/lib/style/base-editor.css"; import vuepress from "@kangc/v-md-editor/lib/theme/vuepress.js"; import "@kangc/v-md-editor/lib/theme/style/vuepress.css"; // 高亮显示 import Prism from "prismjs"; import "prismjs/components/prism-json"; import "prismjs/components/prism-dart"; import "prismjs/components/prism-c"; import "prismjs/components/prism-swift"; import "prismjs/components/prism-kotlin"; import "prismjs/components/prism-java"; // 快捷复制代码 import createCopyCodePlugin from "@kangc/v-md-editor/lib/plugins/copy-code/index"; import "@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css"; // 行号 import createLineNumbertPlugin from "@kangc/v-md-editor/lib/plugins/line-number/index"; VMdEditor.use(vuepress, { Prism, }) .use(createCopyCodePlugin()) .use(createLineNumbertPlugin()); import { defineComponent, ref } from "vue"; export default defineComponent({ name: "App", components: { VMdEditor }, setup() { const content = ref(""); return { content }; }, }); </script> <style> /* 去掉一些按钮 */ .v-md-icon-save, .v-md-icon-fullscreen { display: none; } </style>

这个文件也很简单,整个页面就是一个编辑器<v-md-editor v-model="content"></v-md-editor>,这个markdown编辑器有高亮显示,代码显示行号,复制代码按钮等插件,当然更方便的是可以添加其他的插件丰富这个markdown编辑器的功能.

效果如下

编辑器效果

Vue CLI Plugin Electron Builder

我尝试过用Vite 2.0去搭建Electron项目,但是没有找到类似的ViteElectron结合好使的工具,所以放弃了Vite 2.0的诱惑。如果有小伙伴有推荐可以分享下。

使用vue add electron-builder安装,我选择的是13.0.0Electron的最新版本。

我一般是选择最高的版本,其实这个版本有坑,我后面再想想要不要介绍下这个坑,哈哈。

效果

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyfjdf.html