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 和 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" height="100vh"></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" height="100vh"></v-md-editor>
,这个markdown编辑器有高亮显示,代码显示行号,复制代码按钮等插件,当然更方便的是可以添加其他的插件丰富这个markdown编辑器的功能.
效果如下
vue cli plugin electron builder
我尝试过用vite 2.0去搭建electron项目,但是没有找到类似的vite和electron结合好使的工具,所以放弃了vite 2.0的诱惑。如果有小伙伴有推荐可以分享下。
使用vue add electron-builder
安装,我选择的是13.0.0的electron的最新版本。
我一般是选择最高的版本,其实这个版本有坑,我后面再想想要不要介绍下这个坑,哈哈。
我们看到新加了很多的依赖库,还添加了一个
background.ts
文件。简单介绍下,这个文件执行在主线程,其他的页面都是在渲染线程。渲染线程有很多限制的,有些功能只能在主线程执行,这里就不具体展开了。
执行npm run electron:serve
看效果
至此,就可以看到桌面应用的效果了,并且边修改vue的代码,桌面应用也能实时看到修改后的效果。
优化功能
启动全屏显示
引入screen
import { screen } from "electron";
创建窗口的时候设置为screen大小
<!-- background.ts --> async function createwindow() { const { width, height } = screen.getprimarydisplay().workareasize; const win = new browserwindow({ width, height, // 省略... }); // 省略... }
这样应用启动的时候就是全屏显示了。
修改菜单栏
定义菜单栏
<!-- background.ts --> const template: array<menuitemconstructoroptions> = [ { label: "markdown", submenu: [ { label: "关于", accelerator: "cmdorctrl+w", role: "about", }, { label: "退出程序", accelerator: "cmdorctrl+q", role: "quit", }, ], }, { label: "文件", submenu: [ { label: "打开文件", accelerator: "cmdorctrl+o", click: ( item: menuitem, focusedwindow: browserwindow | undefined, _event: keyboardevent ) => { // todo: 打开文件 }, }, { label: "存储", accelerator: "cmdorctrl+s", click: ( item: menuitem, focusedwindow: browserwindow | undefined, _event: keyboardevent ) => { // todo: 存储内容 }, }, ], }, { label: "编辑", submenu: [ { label: "撤销", accelerator: "cmdorctrl+z", role: "undo", }, { label: "重做", accelerator: "shift+cmdorctrl+z", role: "redo", }, { type: "separator", }, { label: "剪切", accelerator: "cmdorctrl+x", role: "cut", }, { label: "复制", accelerator: "cmdorctrl+c", role: "copy", }, { label: "粘贴", accelerator: "cmdorctrl+v", role: "paste", }, ], }, { label: "窗口", role: "window", submenu: [ { label: "最小化", accelerator: "cmdorctrl+m", role: "minimize", }, { label: "最大化", accelerator: "cmdorctrl+m", click: ( item: menuitem, focusedwindow: browserwindow | undefined, _event: keyboardevent ) => { if (focusedwindow) { focusedwindow.maximize(); } }, }, { type: "separator", }, { label: "切换全屏", accelerator: (function () { if (process.platform === "darwin") { return "ctrl+command+f"; } else { return "f11"; } })(), click: ( item: menuitem, focusedwindow: browserwindow | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars _event: keyboardevent ) => { if (focusedwindow) { focusedwindow.setfullscreen(!focusedwindow.isfullscreen()); } }, }, ], }, { label: "帮助", role: "help", submenu: [ { label: "学习更多", click: function () { shell.openexternal("http://electron.atom.io"); }, }, ], }, ];
具体如何定义参阅electron menu。
打开文件和存储目前还没实现,后面实现。
设置菜单栏
import { menu } from "electron"; app.on("ready", async () => { // 省略... // 创建菜单 menu.setapplicationmenu(menu.buildfromtemplate(template)); });
在
ready
钩子函数中进行设置menu。
效果
编辑器打开markdonw文件的内容
主线程选择文件,将文件路径传给渲染线程
<!-- background.ts --> dialog .showopendialog({ properties: ["openfile"], filters: [{ name: "custom file type", extensions: ["md"] }], }) .then((res) => { if (res && res["filepaths"].length > 0) { const filepath = res["filepaths"][0]; // 将文件传给渲染线程 if (focusedwindow) { focusedwindow.webcontents.send("open-file-path", filepath); } } }) .catch((err) => { console.log(err); });
showopendialog
是打开文件的方法,我们这里指定了只打开md文件;获得文件路径后,通过
focusedwindow.webcontents.send("open-file-path", filepath);
这个方法将文件路径传给渲染线程。
渲染线程取到文件路径,读取文件内容,赋值给markdown编辑器
<!-- app.vue --> import { ipcrenderer } from "electron"; import { readfilesync } from "fs"; export default definecomponent({ // 省略... setup() { const content = ref(""); onmounted(() => { // 1. ipcrenderer.on("open-file-path", (e, filepath: string) => { if (filepath && filepath.length > 0) { // 2. content.value = readfilesync(filepath).tostring(); } }); }); return { content }; }, });
vue添加node支持
<!-- vue.config.js --> module.exports = { pluginoptions: { electronbuilder: { nodeintegration: true, }, }, };
效果
markdonw的内容存入文件
主线程发起向渲染线程获取编辑器内容的请求
<!-- background.js --> if (focusedwindow) { focusedwindow.webcontents.send("get-content", ""); }
渲染线程主线程向返回编辑器的内容
<!-- app.vue --> onmounted(() => { ipcrenderer.on("get-content", () => { ipcrenderer.send("save-content", content.value); }); });
主线程收到内容然后存入文件
<!-- background.ts --> // 存储文件 ipcmain.on("save-content", (event: unknown, content: string) => { if (openedfile.length > 0) { // 直接存储到文件中去 try { writefilesync(openedfile, content); console.log("保存成功"); } catch (error) { console.log("保存失败"); } } else { const options = { title: "保存文件", defaultpath: "new.md", filters: [{ name: "custom file type", extensions: ["md"] }], }; const focusedwindow = browserwindow.getfocusedwindow(); if (focusedwindow) { dialog .showsavedialog(focusedwindow, options) .then((result: electron.savedialogreturnvalue) => { if (result.filepath) { try { writefilesync(result.filepath, content); console.log("保存成功"); openedfile = result.filepath; } catch (error) { console.log("保存失败"); } } }) .catch((error) => { console.log(error); }); } } });
效果
打包
设置应用的名字和图片
<!-- vue.config.js --> module.exports = { pluginoptions: { electronbuilder: { nodeintegration: true, // 添加的设置 builderoptions: { appid: "com.johnny.markdown", productname: "jjmarkdown", // 应用的名字 copyright: "copyright © 2021", //版权声明 mac: { icon: "./public/icon.icns", // icon }, }, }, }, };
icon.icns生成 准备一个1024*1024的图片,同级目录下创建一个为icons.iconset
的文件夹;
创建各种不同尺寸要求的图片文件
sips -z 16 16 icon.png -o icons.iconset/icon_16x16.png sips -z 32 32 icon.png -o icons.iconset/icon_16x16@2x.png sips -z 32 32 icon.png -o icons.iconset/icon_32x32.png sips -z 64 64 icon.png -o icons.iconset/icon_32x32@2x.png sips -z 128 128 icon.png -o icons.iconset/icon_128x128.png sips -z 256 256 icon.png -o icons.iconset/icon_128x128@2x.png sips -z 256 256 icon.png -o icons.iconset/icon_256x256.png sips -z 512 512 icon.png -o icons.iconset/icon_256x256@2x.png sips -z 512 512 icon.png -o icons.iconset/icon_512x512.png sips -z 1024 1024 icon.png -o icons.iconset/icon_512x512@2x.png
获得名为icon.icns的图标文件
iconutil -c icns icons.iconset -o icon.icns
打包
npm run electron:build
结果
获得的dmg文件就可以直接安装使用了。
代码
<!-- background.ts --> "use strict"; import { app, protocol, browserwindow, screen, menu, menuitem, shell, dialog, ipcmain, } from "electron"; import { keyboardevent, menuitemconstructoroptions } from "electron/main"; import { createprotocol } from "vue-cli-plugin-electron-builder/lib"; import installextension, { vuejs3_devtools } from "electron-devtools-installer"; const isdevelopment = process.env.node_env !== "production"; import { writefilesync } from "fs"; let openedfile = ""; // 存储文件 ipcmain.on("save-content", (event: unknown, content: string) => { if (openedfile.length > 0) { // 直接存储到文件中去 try { writefilesync(openedfile, content); console.log("保存成功"); } catch (error) { console.log("保存失败"); } } else { const options = { title: "保存文件", defaultpath: "new.md", filters: [{ name: "custom file type", extensions: ["md"] }], }; const focusedwindow = browserwindow.getfocusedwindow(); if (focusedwindow) { dialog .showsavedialog(focusedwindow, options) .then((result: electron.savedialogreturnvalue) => { if (result.filepath) { try { writefilesync(result.filepath, content); console.log("保存成功"); openedfile = result.filepath; } catch (error) { console.log("保存失败"); } } }) .catch((error) => { console.log(error); }); } } }); const template: array<menuitemconstructoroptions> = [ { label: "markdown", submenu: [ { label: "关于", accelerator: "cmdorctrl+w", role: "about", }, { label: "退出程序", accelerator: "cmdorctrl+q", role: "quit", }, ], }, { label: "文件", submenu: [ { label: "打开文件", accelerator: "cmdorctrl+o", click: ( item: menuitem, focusedwindow: browserwindow | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars _event: keyboardevent ) => { dialog .showopendialog({ properties: ["openfile"], filters: [{ name: "custom file type", extensions: ["md"] }], }) .then((res) => { if (res && res["filepaths"].length > 0) { const filepath = res["filepaths"][0]; // 将文件传给渲染线程 if (focusedwindow) { focusedwindow.webcontents.send("open-file-path", filepath); openedfile = filepath; } } }) .catch((err) => { console.log(err); }); }, }, { label: "存储", accelerator: "cmdorctrl+s", click: ( item: menuitem, focusedwindow: browserwindow | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars _event: keyboardevent ) => { if (focusedwindow) { focusedwindow.webcontents.send("get-content", ""); } }, }, ], }, { label: "编辑", submenu: [ { label: "撤销", accelerator: "cmdorctrl+z", role: "undo", }, { label: "重做", accelerator: "shift+cmdorctrl+z", role: "redo", }, { type: "separator", }, { label: "剪切", accelerator: "cmdorctrl+x", role: "cut", }, { label: "复制", accelerator: "cmdorctrl+c", role: "copy", }, { label: "粘贴", accelerator: "cmdorctrl+v", role: "paste", }, ], }, { label: "窗口", role: "window", submenu: [ { label: "最小化", accelerator: "cmdorctrl+m", role: "minimize", }, { label: "最大化", accelerator: "cmdorctrl+m", click: ( item: menuitem, focusedwindow: browserwindow | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars _event: keyboardevent ) => { if (focusedwindow) { focusedwindow.maximize(); } }, }, { type: "separator", }, { label: "切换全屏", accelerator: (function () { if (process.platform === "darwin") { return "ctrl+command+f"; } else { return "f11"; } })(), click: ( item: menuitem, focusedwindow: browserwindow | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars _event: keyboardevent ) => { if (focusedwindow) { focusedwindow.setfullscreen(!focusedwindow.isfullscreen()); } }, }, ], }, { label: "帮助", role: "help", submenu: [ { label: "学习更多", click: function () { shell.openexternal("http://electron.atom.io"); }, }, ], }, ]; protocol.registerschemesasprivileged([ { scheme: "app", privileges: { secure: true, standard: true } }, ]); async function createwindow() { const { width, height } = screen.getprimarydisplay().workareasize; const win = new browserwindow({ width, height, webpreferences: { nodeintegration: true, contextisolation: false, }, }); if (process.env.webpack_dev_server_url) { // load the url of the dev server if in development mode await win.loadurl(process.env.webpack_dev_server_url as string); if (!process.env.is_test) win.webcontents.opendevtools(); } else { createprotocol("app"); // load the index.html when not in development win.loadurl("app://./index.html"); } } // quit when all windows are closed. app.on("window-all-closed", () => { // on macos it is common for applications and their menu bar // to stay active until the user quits explicitly with cmd + q if (process.platform !== "darwin") { app.quit(); } }); app.on("activate", () => { // on macos it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (browserwindow.getallwindows().length === 0) createwindow(); }); // this method will be called when electron has finished // initialization and is ready to create browser windows. // some apis can only be used after this event occurs. app.on("ready", async () => { if (isdevelopment && !process.env.is_test) { // install vue devtools try { await installextension(vuejs3_devtools); } catch (e) { console.error("vue devtools failed to install:", e.tostring()); } } createwindow(); // 创建菜单 menu.setapplicationmenu(menu.buildfromtemplate(template)); }); // exit cleanly on request from parent process in development mode. if (isdevelopment) { if (process.platform === "win32") { process.on("message", (data) => { if (data === "graceful-exit") { app.quit(); } }); } else { process.on("sigterm", () => { app.quit(); }); } }
到此这篇关于vue3和electron实现桌面端应用详解的文章就介绍到这了,更多相关vue3 electron 桌面端应用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!