前端实战:electron+vue3+ts开发桌面端便签应用

 

前端时间我的一个朋友为了快速熟悉 Vue3 开发, 特意使用 electron+vue3+ts 开发了一个桌面端应用, 并在 github 上开源了, 接下来我就带大家一起了解一下这个项目, 在文章末尾我会放 github的地址, 大家如果想学习vue3 + ts + electron 开发, 可以本地 clone 学习参考一下.


image.png

技术栈

以上是我们看到的便签软件使用界面, 整体技术选型如下:

  • 脚手架 vue-cli

  • 前端框架和语言规范 vue + typescript

  • 桌面端开发框架 electron

  • electron支持插件 vue-cli-plugin-electron-builder

  • 数据库 NeDB | 一款NoSQL嵌入式数据库

  • 代码格式规范 eslint

接下来我们来看看具体的演示效果:


具体实现过程, 内容很长, 建议先点赞收藏, 再一步步学习, 接下来会就该项目的每一个重点细节做详细的分析.

开发思路

  1. 页面:

  • 列表页index.vue 头部、搜索、内容部分,只能有一个列表页存在

  • 设置页setting.vue 设置内容和软件信息,和列表页一样只能有一个存在

  • 编辑页 editor.vue icons功能和背景颜色功能,可以多个编辑页同时存在

  • 动效:

    • 打开动效,有一个放大、透明度的过渡,放不了动图这里暂时不演示了。

    • 标题过渡效果

    • 切换indexsetting时头部不变,内容过渡

  • 数据储存:数据的创建和更新都在编辑页editor.vue进行,这个过程中在储存进nedb之后才通信列表页index.vue更新内容,考虑到性能问题,这里使用了防抖防止连续性的更新而导致卡顿(不过貌似没有这个必要。。也算是一个小功能吧,然后可以设置这个更新速度)

  • 错误采集:采集在使用中的错误并弹窗提示

  • 编辑显示:document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。

  • 在开发的时候还遇到过好多坑,这些都是在electron环境中才有,比如

    1. @input触发2次,加上v-model触发3次。包括创建一个新的electron框架也是这样,别人电脑上不会出现这个问题,猜测是electron缓存问题

    2. vue3碰到空属性报错时无限报错,在普通浏览器(edge和chrome)是正常一次

    3. 组件无法正常渲染不报错,只在控制台报异常

    4. 打包后由于electron的缓存导致打开需要10秒左右,清除c盘软件缓存后正常

    其他的不记得了。。

    这里暂时不提供vue3和electron介绍,有需要的可以先看看社区其他的有关文章或者后期再详细专门提供。软件命名为i-notes

    vue3中文教程 vue3js.cn/docs/zh/gui…[1] electron教程 www.electronjs.org/[2]
    typescript教程 www.typescriptlang.org/[3]

    electron-vue里面的包环境太低了,所以是手动配置electron+vue3(虽然说是手动。。其实就两个步骤)

    目录结构

    1.  
      electron-vue-notes
    2.  
      ├── public
    3.  
      │   ├── css
    4.  
      │   ├── font
    5.  
      │   └── index.html
    6.  
      ├── src
    7.  
      │   ├── assets
    8.  
      │   │   └── empty-content.svg
    9.  
      │   ├── components
    10.  
      │   │   ├── message
    11.  
      │   │   ├── rightClick
    12.  
      │   │   ├── editor.vue
    13.  
      │   │   ├── header.vue
    14.  
      │   │   ├── input.vue
    15.  
      │   │   ├── messageBox.vue
    16.  
      │   │   ├── switch.vue
    17.  
      │   │   └── tick.vue
    18.  
      │   ├── config
    19.  
      │   │   ├── browser.options.ts
    20.  
      │   │   ├── classNames.options.ts
    21.  
      │   │   ├── editorIcons.options.ts
    22.  
      │   │   ├── index.ts
    23.  
      │   │   └── shortcuts.keys.ts
    24.  
      │   ├── inotedb
    25.  
      │   │   └── index.ts
    26.  
      │   ├── less
    27.  
      │   │   └── index.less
    28.  
      │   ├── router
    29.  
      │   │   └── index.ts
    30.  
      │   ├── script
    31.  
      │   │   └── deleteBuild.js
    32.  
      │   ├── store
    33.  
      │   │   ├── exeConfig.state.ts
    34.  
      │   │   └── index.ts
    35.  
      │   ├── utils
    36.  
      │   │   ├── errorLog.ts
    37.  
      │   │   └── index.ts
    38.  
      │   ├── views
    39.  
      │   │   ├── editor.vue
    40.  
      │   │   ├── index.vue
    41.  
      │   │   ├── main.vue
    42.  
      │   │   └── setting.vue
    43.  
      │   ├── App.vue
    44.  
      │   ├── background.ts
    45.  
      │   ├── main.ts
    46.  
      │   └── shims-vue.d.ts
    47.  
      ├── .browserslistrc
    48.  
      ├── .eslintrc.js
    49.  
      ├── .prettierrc.js
    50.  
      ├── babel.config.js
    51.  
      ├── inoteError.log
    52.  
      ├── LICENSE
    53.  
      ├── package-lock.json
    54.  
      ├── package.json
    55.  
      ├── README.md
    56.  
      ├── tsconfig.json
    57.  
      ├── vue.config.js
    58.  
      └── yarn.lock 

    使用脚手架搭建vue3环境

    没有脚手架的可以先安装脚手架

    npm install -g @vue/cli 
    

    创建vue3项目

    1.  
      vue create electron-vue-notes
    2.  
       
    3.  
      # 后续
    4.  
      ? Please pick a preset: (Use arrow keys)
    5.  
        Default ([Vue 2] babel, eslint)
    6.  
        Default (Vue 3 Preview) ([Vue 3] babel, eslint)
    7.  
      > Manually select features 
    8.  
      # 手动选择配置
    9.  
       
    10.  
      # 后续所有配置
    11.  
      ? Please pick a preset: Manually select features
    12.  
      ? Check the features needed for your project: Choose Vue version, Babel, TS, Router, CSS Pre-processors, Linter
    13.  
      ? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
    14.  
      ? Use class-style component syntax? Yes
    15.  
      ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
    16.  
      ? Use history mode for router? (Requires proper server setup for index fallback in production) No
    17.  
      ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
    18.  
      ? Pick a linter / formatter config: Prettier
    19.  
      ? Pick additional lint features: Lint on save, Lint and fix on commit
    20.  
      ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
    21.  
      ? Save this as a preset for future projects? (y/N) n 

    创建完之后的目录是这样的

    1.  
      electron-vue-notes
    2.  
      ├── public
    3.  
      │   ├── favicon.ico
    4.  
      │   └── index.html
    5.  
      ├── src
    6.  
      │   ├── assets
    7.  
      │   │   └── logo.png
    8.  
      │   ├── components
    9.  
      │   │   └── HelloWorld.vue
    10.  
      │   ├── router
    11.  
      │   │   └── index.ts
    12.  
      │   ├── views
    13.  
      │   │   ├── About.vue
    14.  
      │   │   └── Home.vue
    15.  
      │   ├── App.vue
    16.  
      │   ├── main.ts
    17.  
      │   └── shims-vue.d.ts
    18.  
      ├── .browserslistrc
    19.  
      ├── .eslintrc.js
    20.  
      ├── babel.config.js
    21.  
      ├── package.json
    22.  
      ├── README.md
    23.  
      ├── tsconfig.json
    24.  
      └── yarn.lock 

    安装electron的依赖

    1.  
      # yarn
    2.  
      yarn add vue-cli-plugin-electron-builder electron
    3.  
       
    4.  
      # npm 或 cnpm
    5.  
      npm i vue-cli-plugin-electron-builder electron 

    安装完之后完善一些配置,比如别名eslintprettier等等基础配置,还有一些颜色icons等等具体可以看下面

    项目的一些基础配置

    eslint

    使用eslint主要是规范代码风格,不推荐tslint是因为tslint已经不更新了,tslint也推荐使用eslint 安装eslint

    npm i eslint -g 
    

    进入项目之后初始化eslint

    1.  
      eslint --init
    2.  
       
    3.  
      # 后续配置
    4.  
      ? How would you like to use ESLint? To check syntax and find problems
    5.  
      ? What type of modules does your project use? JavaScript modules (import/export)
    6.  
      ? Which framework does your project use? Vue.js
    7.  
      ? Does your project use TypeScript? Yes
    8.  
      ? Where does your code run? Browser, Node
    9.  
      ? What format do you want your config file to be in? JavaScript
    10.  
      The config that you've selected requires the following dependencies:
    11.  
       
    12.  
      eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
    13.  
      ? Would you like to install them now with npm? (Y/n) y 
    14.  
       

    修改eslint配置,·.eslintrc.js,规则rules可以根据自己的喜欢配置 eslint.org/docs/user-g…[4]

    1.  
      module.exports = {
    2.  
        root: true,
    3.  
        env: {
    4.  
          node: true
    5.  
        },
    6.  
        extends: [
    7.  
          'plugin:vue/vue3-essential',
    8.  
          'eslint:recommended',
    9.  
          'plugin:prettier/recommended',
    10.  
          'plugin:@typescript-eslint/eslint-recommended',
    11.  
          '@vue/typescript/recommended',
    12.  
          '@vue/prettier',
    13.  
          '@vue/prettier/@typescript-eslint'
    14.  
        ],
    15.  
        parserOptions: {
    16.  
          ecmaVersion: 2020
    17.  
        },
    18.  
        rules: {
    19.  
          quotes: [1, 'single'],
    20.  
          semi: 1,
    21.  
          '@typescript-eslint/camelcase': 0,
    22.  
          '@typescript-eslint/no-explicit-any': 0,
    23.  
          'no-irregular-whitespace': 2,
    24.  
          'no-case-declarations': 0,
    25.  
          'no-undef': 0,
    26.  
          'eol-last': 1,
    27.  
          'block-scoped-var': 2,
    28.  
          'comma-dangle': [2, 'never'],
    29.  
          'no-dupe-keys': 2,
    30.  
          'no-empty': 1,
    31.  
          'no-extra-semi': 2,
    32.  
          'no-multiple-empty-lines': [1, { max: 1, maxEOF: 1 }],
    33.  
          'no-trailing-spaces': 1,
    34.  
          'semi-spacing': [2, { before: false, after: true }],
    35.  
          'no-unreachable': 1,
    36.  
          'space-infix-ops': 1,
    37.  
          'spaced-comment': 1,
    38.  
          'no-var': 2,
    39.  
          'no-multi-spaces': 2,
    40.  
          'comma-spacing': 1
    41.  
        }
    42.  
      }; 

    prettier

    在根目录增加.prettierrc.js配置,根据自己的喜好进行配置,单行多少个字符、单引号、分号、逗号结尾等等

    1.  
      module.exports = {
    2.  
        printWidth: 120,
    3.  
        singleQuote: true,
    4.  
        semi: true,
    5.  
        trailingComma: 'none'
    6.  
      }; 

    tsconfig.json

    如果这里没有配置识别@/路径的话,在项目中使用会报错

    1.  
      "paths": {
    2.  
        "@/*": [
    3.  
          "src/*"
    4.  
        ]
    5.  

    package.json

    1.  
      "author": "heiyehk",
    2.  
      "description": "I便笺个人开发者heiyehk独立开发,在Windows中更方便的记录文字。",
    3.  
      "main": "background.js",
    4.  
      "scripts": {
    5.  
        "lint": "vue-cli-service lint",
    6.  
        "electron:build": "vue-cli-service electron:build",
    7.  
        "electron:serve": "vue-cli-service electron:serve"
    8.  

    配置入口文件background.ts

    因为需要做一些打开和关闭的动效,因此我们需要配置electronframe无边框透明transparent的属性

    1.  
      /* eslint-disable @typescript-eslint/no-empty-function */
    2.  
      'use strict';
    3.  
       
    4.  
      import { app, protocol, BrowserWindow, globalShortcut } from 'electron';
    5.  
      import {
    6.  
        createProtocol
    7.  
        // installVueDevtools
    8.  
      } from 'vue-cli-plugin-electron-builder/lib';
    9.  
       
    10.  
      const isDevelopment = process.env.NODE_ENV !== 'production';
    11.  
       
    12.  
      let win: BrowserWindow | null;
    13.  
      protocol.registerSchemesAsPrivileged([
    14.  
        {
    15.  
          scheme: 'app',
    16.  
          privileges: {
    17.  
            secure: true,
    18.  
            standard: true
    19.  
          }
    20.  
        }
    21.  
      ]);
    22.  
       
    23.  
      function createWindow() {
    24.  
        win = new BrowserWindow({
    25.  
          frame: false, // 无边框
    26.  
          hasShadow: false,
    27.  
          transparent: true, // 透明
    28.  
           950,
    29.  
          height: 600,
    30.  
          webPreferences: {
    31.  
            enableRemoteModule: true,
    32.  
            nodeIntegration: true
    33.  
          }
    34.  
        });
    35.  
       
    36.  
        if (process.env.WEBPACK_DEV_SERVER_URL) {
    37.  
          win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    38.  
          if (!process.env.IS_TEST) win.webContents.openDevTools();
    39.  
        } else {
    40.  
          createProtocol('app');
    41.  
          win.loadURL('http://localhost:8080');
    42.  
        }
    43.  
       
    44.  
        win.on('closed', () => {
    45.  
          win = null;
    46.  
        });
    47.  
      }
    48.  
       
    49.  
      app.on('window-all-closed', () => {
    50.  
        if (process.platform !== 'darwin') {
    51.  
          app.quit();
    52.  
        }
    53.  
      });
    54.  
       
    55.  
      app.on('activate', () => {
    56.  
        if (win === null) {
    57.  
          createWindow();
    58.  
        }
    59.  
      });
    60.  
       
    61.  
      app.on('ready', async () => {
    62.  
        // 这里注释掉是因为会安装tools插件,需要屏蔽掉,有能力的话可以打开注释
    63.  
        // if (isDevelopment && !process.env.IS_TEST) {
    64.  
        //   try {
    65.  
        //     await installVueDevtools();
    66.  
        //   } catch (e) {
    67.  
        //     console.error('Vue Devtools failed to install:', e.toString());
    68.  
        //   }
    69.  
        // }
    70.  
        createWindow();
    71.  
      });
    72.  
       
    73.  
      if (isDevelopment) {
    74.  
        if (process.platform === 'win32') {
    75.  
          process.on('message', data => {
    76.  
            if (data === 'graceful-exit') {
    77.  
              app.quit();
    78.  
            }
    79.  
          });
    80.  
        } else {
    81.  
          process.on('SIGTERM', () => {
    82.  
            app.quit();
    83.  
          });
    84.  
        }
    85.  

    启动

    yarn electron:serve 
    

    到这里配置就算是成功搭建好这个窗口了,但是还有一些其他细节需要进行配置,比如electron打包配置,模块化的配置等等

    常规配置

    这里配置一些常用的开发内容和一些轮子代码, 大家可以参考 reset.csss 和 common.css 这两个文件.

    config

    这个对应项目中的config文件夹

    1.  
      config
    2.  
      ├── browser.options.ts # 窗口的配置
    3.  
      ├── classNames.options.ts # 样式名的配置,背景样式都通过这个文件渲染
    4.  
      ├── editorIcons.options.ts # 编辑页面的一些editor图标
    5.  
      ├── index.ts # 导出
    6.  
      └── shortcuts.keys.ts # 禁用的一些快捷键,electron是基于chromium浏览器,所以也存在一些浏览器快捷键比如F5 

    browser.options

    这个文件的主要作用就是配置主窗口和编辑窗口区分开发正式的配置,宽高等等,以及要显示的主页面

    1.  
      /**
    2.  
       * 软件数据和配置
    3.  
       * C:Users{用户名}AppDataRoaming
    4.  
       * 共享
    5.  
       * C:ProgramDataIntelShaderCachei-notes{xx}
    6.  
       * 快捷方式
    7.  
       * C:Users{用户名}AppDataRoamingMicrosoftWindowsRecent
    8.  
       * 电脑自动创建缓存
    9.  
       * C:WindowsPrefetchI-NOTES.EXE{xx}
    10.  
       */
    11.  
       
    12.  
      /** */
    13.  
      const globalEnv = process.env.NODE_ENV;
    14.  
       
    15.  
      const devWid = globalEnv === 'development' ? 950 : 0;
    16.  
      const devHei = globalEnv === 'development' ? 600 : 0;
    17.  
       
    18.  
      // 底部icon: 40*40
    19.  
      const editorWindowOptions = {
    20.  
         devWid || 290,
    21.  
        height: devHei || 350,
    22.  
        minWidth: 250
    23.  
      };
    24.  
       
    25.  
      /**
    26.  
       * BrowserWindow的配置项
    27.  
       * @param type 单独给编辑窗口的配置
    28.  
       */
    29.  
      const browserWindowOption = (type?: 'editor'): Electron.BrowserWindowConstructorOptions => {
    30.  
        const commonOptions = {
    31.  
          minHeight: 48,
    32.  
          frame: false,
    33.  
          hasShadow: true,
    34.  
          transparent: true,
    35.  
          webPreferences: {
    36.  
            enableRemoteModule: true,
    37.  
            nodeIntegration: true
    38.  
          }
    39.  
        };
    40.  
        if (!type) {
    41.  
          return {
    42.  
             devWid || 350,
    43.  
            height: devHei || 600,
    44.  
            minWidth: 320,
    45.  
            ...commonOptions
    46.  
          };
    47.  
        }
    48.  
        return {
    49.  
          ...editorWindowOptions,
    50.  
          ...commonOptions
    51.  
        };
    52.  
      };
    53.  
       
    54.  
      /**
    55.  
       * 开发环境: http://localhost:8080
    56.  
       * 正式环境: file://${__dirname}/index.html
    57.  
       */
    58.  
      const winURL = globalEnv === 'development' ? 'http://localhost:8080' : `file://${__dirname}/index.html`;
    59.  
       
    60.  
      export { browserWindowOption, winURL }; 

    router

    增加meta中的title属性,显示在软件上方头部

    1.  
      import { createRouter, createWebHashHistory } from 'vue-router';
    2.  
      import { RouteRecordRaw } from 'vue-router';
    3.  
      import main from '../views/main.vue';
    4.  
       
    5.  
      const routes: Array<RouteRecordRaw> = [
    6.  
        {
    7.  
          path: '/',
    8.  
          name: 'main',
    9.  
          component: main,
    10.  
          children: [
    11.  
            {
    12.  
              path: '/',
    13.  
              name: 'index',
    14.  
              component: () => import('../views/index.vue'),
    15.  
              meta: {
    16.  
                title: 'I便笺'
    17.  
              }
    18.  
            },
    19.  
            {
    20.  
              path: '/editor',
    21.  
              name: 'editor',
    22.  
              component: () => import('../views/editor.vue'),
    23.  
              meta: {
    24.  
                title: ''
    25.  
              }
    26.  
            },
    27.  
            {
    28.  
              path: '/setting',
    29.  
              name: 'setting',
    30.  
              component: () => import('../views/setting.vue'),
    31.  
              meta: {
    32.  
                title: '设置'
    33.  
              }
    34.  
            }
    35.  
          ]
    36.  
        }
    37.  
      ];
    38.  
       
    39.  
      const router = createRouter({
    40.  
        history: createWebHashHistory(process.env.BASE_URL),
    41.  
        routes
    42.  
      });
    43.  
       
    44.  
      export default router; 

    main.vue

    main.vue文件主要是作为一个整体框架,考虑到页面切换时候的动效,分为头部和主体部分,头部作为一个单独的组件处理,内容区域使用router-view渲染。html部分,这里和vue2.x有点区别的是,在vue2.x中可以直接

    1.  
      // bad
    2.  
      <transition name="fade">
    3.  
        <keep-alive>
    4.  
          <router-view />
    5.  
        </keep-alive>
    6.  
      </transition> 

    上面的这种写法在vue3中会在控制台报异常,记不住写法的可以看看控制台????????

    1.  
      <router-view v-slot="{ Component }">
    2.  
        <transition name="main-fade">
    3.  
          <div class="transition" :key="routeName">
    4.  
            <keep-alive>
    5.  
              <component :is="Component" />
    6.  
            </keep-alive>
    7.  
          </div>
    8.  
        </transition>
    9.  
      </router-view> 

    然后就是ts部分了,使用vue3的写法去写,script标签注意需要写上lang="ts"代表是ts语法。router的写法也不一样,虽然在vue3中还能写vue2的格式,但是不推荐使用。这里是获取routename属性,来进行一个页面过渡的效果。

    1.  
      <script lang="ts">
    2.  
      import { defineComponent, ref, onBeforeUpdate } from 'vue';
    3.  
      import { useRoute } from 'vue-router';
    4.  
      import Header from '@/components/header.vue';
    5.  
       
    6.  
      export default defineComponent({
    7.  
        components: {
    8.  
          Header
    9.  
        },
    10.  
        setup() {
    11.  
          const routeName = ref(useRoute().name);
    12.  
       
    13.  
          onBeforeUpdate(() => {
    14.  
            routeName.value = useRoute().name;
    15.  
          });
    16.  
       
    17.  
          return {
    18.  
            routeName
    19.  
          };
    20.  
        }
    21.  
      });
    22.  
      </script> 

    less部分

    1.  
      <style lang="less" scoped>
    2.  
      .main-fade-enter,
    3.  
      .main-fade-leave-to {
    4.  
      display: none;
    5.  
      opacity: 0;
    6.  
      animation: main-fade 0.4s reverse;
    7.  
      }
    8.  
      .main-fade-enter-active,
    9.  
      .main-fade-leave-active {
    10.  
      opacity: 0;
    11.  
      animation: main-fade 0.4s;
    12.  
      }
    13.  
      @keyframes main-fade {
    14.  
      from {
    15.  
      opacity: 0;
    16.  
      transform: scale(0.96);
    17.  
      }
    18.  
      to {
    19.  
      opacity: 1;
    20.  
      transform: scale(1);
    21.  
      }
    22.  
      }
    23.  
      </style>

    以上就是main.vue的内容,在页面刷新或者进入的时候根据useRouter().name的切换进行放大的过渡效果,后面的内容会更简洁一点。

    header.vue

    onBeforeRouteUpdate

    头部组件还有一个标题过渡的效果,根据路由导航获取当前路由的mate.title变化进行过渡效果。vue3中路由守卫需要从vue-route导入使用。

    1.  
      import { onBeforeRouteUpdate, useRoute } from 'vue-router';
    2.  
      ...
    3.  
      onBeforeRouteUpdate((to, from, next) => {
    4.  
        title.value = to.meta.title;
    5.  
        currentRouteName.value = to.name;
    6.  
        next();
    7.  
      }); 

    computed

    这里是计算不同的路由下标题内边距的不同,首页是有个设置入口的按钮,而设置页面是只有两个按钮,computed会返回一个你需要的新的值

    1.  
      // 获取首页的内边距
    2.  
      const computedPaddingLeft = computed(() => {
    3.  
        return currentRouteName.value === 'index' ? 'padding-left: 40px;' : '';
    4.  
      }); 

    emit子传父和props父传子

    vue3没有了this,那么要使用emit怎么办呢?在入口setup中有2个参数

    setup(props, content) {} 
    

    props是父组件传给子组件的内容,props常用的emitprops都在content中。

    ????这里需要注意的是,使用propsemit需要先定义,才能去使用,并且会在vscode中直接调用时辅助弹窗显示

    props示例

    emit示例

    1.  
      export default defineComponent({
    2.  
        props: {
    3.  
          test: String
    4.  
        },
    5.  
        emits: ['option-click', 'on-close'],
    6.  
        // 如果只用emit的话可以使用es6解构
    7.  
        // 如:setup(props, { emit })
    8.  
        setup(props, content) {
    9.  
          console.log(props.test, content.emit('option-click'));
    10.  
        }
    11.  
      }) 

    electron打开窗口

    1.  
      import { browserWindowOption } from '@/config';
    2.  
      import { createBrowserWindow, transitCloseWindow } from '@/utils';
    3.  
      ...
    4.  
      const editorWinOptions = browserWindowOption('editor');
    5.  
      // 打开新窗口
    6.  
      const openNewWindow = () => {
    7.  
        createBrowserWindow(editorWinOptions, '/editor');
    8.  
      }; 

    electron图钉固定屏幕前面

    先获取当前屏幕实例

    ????这里需要注意的是,需要从remote获取当前窗口信息

    判断当前窗口是否在最前面isAlwaysOnTop(),然后通过setAlwaysOnTop()属性设置当前窗口最前面。

    1.  
      import { remote } from 'electron';
    2.  
      ...
    3.  
      // 获取窗口固定状态
    4.  
      let isAlwaysOnTop = ref(false);
    5.  
      const currentWindow = remote.getCurrentWindow();
    6.  
      isAlwaysOnTop.value = currentWindow.isAlwaysOnTop();
    7.  
       
    8.  
      // 固定前面
    9.  
      const drawingPin = () => {
    10.  
        if (isAlwaysOnTop.value) {
    11.  
          currentWindow.setAlwaysOnTop(false);
    12.  
          isAlwaysOnTop.value = false;
    13.  
        } else {
    14.  
          currentWindow.setAlwaysOnTop(true);
    15.  
          isAlwaysOnTop.value = true;
    16.  
        }
    17.  
      }; 

    electron关闭窗口

    这里是在utils封装了通过对dom的样式名操作,达到一个退出的过渡效果,然后再关闭。

    1.  
      // 过渡关闭窗口
    2.  
      export const transitCloseWindow = (): void => {
    3.  
        document.querySelector('#app')?.classList.remove('app-show');
    4.  
        document.querySelector('#app')?.classList.add('app-hide');
    5.  
        remote.getCurrentWindow().close();
    6.  
      }; 

    noteDb数据库

    安装nedb数据库,文档: www.w3cschool.cn/nedbintro/n…[5]

    yarn add nedb @types/nedb 
    

    数据储存在nedb中,定义字段,并在根目录的shims-vue.d.ts加入类型

    1.  
      /**
    2.  
       * 储存数据库的
    3.  
       */
    4.  
      interface DBNotes {
    5.  
        className: string; // 样式名
    6.  
        content: string; // 内容
    7.  
        readonly createdAt: Date; // 创建时间,这个时间是nedb自动生成的
    8.  
        readonly uid: string; // uid,utils中的方法生成
    9.  
        readonly updatedAt: Date; // update,自动创建的
    10.  
        readonly _id: string; // 自动创建的
    11.  

    对nedb的封装

    自我感觉这里写的有点烂。。。勿喷,持续学习中

    这里的QueryDBshims-vue.d.ts定义好的类型

    这里的意思是QueryDB<T>是一个对象,然后这个对象传入一个泛型T,这里keyof T获取这个对象的key(属性)值,?:代表这个key可以是undefined,表示可以不存在。T[K]表示从这个对象中获取这个K的值。

    1.  
      type QueryDB<T> = {
    2.  
        [K in keyof T]?: T[K];
    3.  
      }; 
    1.  
      import Datastore from 'nedb';
    2.  
      import path from 'path';
    3.  
      import { remote } from 'electron';
    4.  
       
    5.  
      /**
    6.  
       * @see https://www.npmjs.com/package/nedb
    7.  
       */
    8.  
      class INoteDB<G = any> {
    9.  
        /**
    10.  
         * 默认储存位置
    11.  
         * C:Users{Windows User Name}AppDataRoamingi-notes
    12.  
         */
    13.  
        // dbPath = path.join(remote.app.getPath('userData'), 'db/inote.db');
    14.  
        // dbPath = './db/inote.db';
    15.  
        dbPath = this.path;
    16.  
       
    17.  
        _db: Datastore<Datastore.DataStoreOptions> = this.backDatastore;
    18.  
       
    19.  
        get path() {
    20.  
          if (process.env.NODE_ENV === 'development') {
    21.  
            return path.join(__dirname, 'db/inote.db');
    22.  
          }
    23.  
          return path.join(remote.app.getPath('userData'), 'db/inote.db');
    24.  
        }
    25.  
       
    26.  
        get backDatastore() {
    27.  
          return new Datastore({
    28.  
            /**
    29.  
             * autoload
    30.  
             * default: false
    31.  
             * 当数据存储被创建时,数据将自动从文件中加载到内存,不必去调用loadDatabase
    32.  
             * 注意所有命令操作只有在数据加载完成后才会被执行
    33.  
             */
    34.  
            autoload: true,
    35.  
            filename: this.dbPath,
    36.  
            timestampData: true
    37.  
          });
    38.  
        }
    39.  
       
    40.  
        refreshDB() {
    41.  
          this._db = this.backDatastore;
    42.  
        }
    43.  
       
    44.  
        insert<T extends G>(doc: T) {
    45.  
          return new Promise((resolve: (value: T) => void) => {
    46.  
            this._db.insert(doc, (error: Error | null, document: T) => {
    47.  
              if (!error) resolve(document);
    48.  
            });
    49.  
          });
    50.  
        }
    51.  
       
    52.  
        /**
    53.  
         * db.find(query)
    54.  
         * @param {Query<T>} query:object类型,查询条件,可以使用空对象{}。
    55.  
         * 支持使用比较运算符($lt, $lte, $gt, $gte, $in, $nin, $ne)
    56.  
         * 逻辑运算符($or, $and, $not, $where)
    57.  
         * 正则表达式进行查询。
    58.  
         */
    59.  
        find(query: QueryDB<DBNotes>) {
    60.  
          return new Promise((resolve: (value: DBNotes[]) => void) => {
    61.  
            this._db.find(query, (error: Error | null, document: DBNotes[]) => {
    62.  
              if (!error) resolve(document as DBNotes[]);
    63.  
            });
    64.  
          });
    65.  
        }
    66.  
       
    67.  
        /**
    68.  
         * db.findOne(query)
    69.  
         * @param query
    70.  
         */
    71.  
        findOne(query: QueryDB<DBNotes>) {
    72.  
          return new Promise((resolve: (value: DBNotes) => void) => {
    73.  
            this._db.findOne(query, (error: Error | null, document) => {
    74.  
              if (!error) resolve(document as DBNotes);
    75.  
            });
    76.  
          });
    77.  
        }
    78.  
       
    79.  
        /**
    80.  
         * db.remove(query, options)
    81.  
         * @param {Record<keyof DBNotes, any>} query
    82.  
         * @param {Nedb.RemoveOptions} options
    83.  
         * @return {BackPromise<number>}
    84.  
         */
    85.  
        remove(query: QueryDB<DBNotes>, options?: Nedb.RemoveOptions) {
    86.  
          return new Promise((resolve: (value: number) => void) => {
    87.  
            if (options) {
    88.  
              this._db.remove(query, options, (error: Error | null, n: number) => {
    89.  
                if (!error) resolve(n);
    90.  
              });
    91.  
            } else {
    92.  
              this._db.remove(query, (error: Error | null, n: number) => {
    93.  
                if (!error) resolve(n);
    94.  
              });
    95.  
            }
    96.  
          });
    97.  
        }
    98.  
       
    99.  
        update<T extends G>(query: T, updateQuery: T, options: Nedb.UpdateOptions = {}) {
    100.  
          return new Promise((resolve: (value: T) => void) => {
    101.  
            this._db.update(
    102.  
              query,
    103.  
              updateQuery,
    104.  
              options,
    105.  
              (error: Error | null, numberOfUpdated: number, affectedDocuments: T) => {
    106.  
                if (!error) resolve(affectedDocuments);
    107.  
              }
    108.  
            );
    109.  
          });
    110.  
        }
    111.  
      }
    112.  
       
    113.  
      export default new INoteDB(); 

    使用refreactive代替vuex,并用watch监听

    创建exeConfig.state.ts

    refreactive引入的方式就可以达到vuexstate效果,这样就可以完全舍弃掉vuex。比如软件配置,创建exeConfig.state.tsstore中,这样在外部.vue文件中进行更改也能去更新视图。

    1.  
      import { reactive, watch } from 'vue';
    2.  
       
    3.  
      const exeConfigLocal = localStorage.getItem('exeConfig');
    4.  
       
    5.  
      export let exeConfig = reactive({
    6.  
        syncDelay: 1000,
    7.  
        ...
    8.  
        switchStatus: {
    9.  
          /**
    10.  
           * 开启提示
    11.  
           */
    12.  
          textTip: true
    13.  
        }
    14.  
      });
    15.  
       
    16.  
      if (exeConfigLocal) {
    17.  
        exeConfig = reactive(JSON.parse(exeConfigLocal));
    18.  
      else {
    19.  
        localStorage.setItem('exeConfig', JSON.stringify(exeConfig));
    20.  
      }
    21.  
       
    22.  
      watch(exeConfig, e => {
    23.  
        localStorage.setItem('exeConfig', JSON.stringify(e));
    24.  
      }); 

    vuex番外

    vuex的使用是直接在项目中引入useStore,但是是没有state类型提示的,所以需要手动去推导state的内容。这里的S代表state的类型,然后传入vuexexport declare class Store<S> { readonly state: S; }

    想要查看某个值的类型的时候在vscode中ctrl+鼠标左键点进去就能看到,或者鼠标悬浮该值

    1.  
      declare module 'vuex' {
    2.  
        type StoreStateType = typeof store.state;
    3.  
        export function useStore<S = StoreStateType>(): Store<S>;
    4.  

    index.vue

    • 这里在防止没有数据的时候页面空白闪烁,使用一个图片和列表区域去控制显示,拿到数据之后就显示列表,否则就只显示图片。

    • 在这个页面对editor.vue进行了createNewNote创建便笺笔记、updateNoteItem_className更新类型更改颜色、updateNoteItem_content更新内容、removeEmptyNoteItem删除、whetherToOpen是否打开(在editor中需要打开列表的操作)通信操作

    • 以及对软件失去焦点进行监听getCurrentWindow().on('blur'),如果失去焦点,那么在右键弹窗打开的情况下进行去除。

    • deleteActiveItem_{uid}删除便笺笔记内容,这里在component封装了一个弹窗组件messageBox,然后在弹窗的时候提示是否删除不在询问的功能操作。

      • ????如果勾选不在询问,那么在store=>exeConfig.state中做相应的更改

      • 这里在设置中会进行详细的介绍

    开发一个vue3右键弹窗插件

    vue3也发布了有段时间了,虽然还没有完全稳定,但后面的时间出现的插件开发方式说不定也会多起来。插件开发思路

    1. 定义好插件类型,比如需要哪些属性MenuOptions

    2. 判断是否需要在触发之后立即关闭还是继续显示

    3. 在插入body时判断是否存在,否则就删除重新显示

    1.  
      import { createApp, h, App, VNode, RendererElement, RendererNode } from 'vue';
    2.  
      import './index.css';
    3.  
       
    4.  
      type ClassName = string | string[];
    5.  
       
    6.  
      interface MenuOptions {
    7.  
        /**
    8.  
         * 文本
    9.  
         */
    10.  
        text: string;
    11.  
       
    12.  
        /**
    13.  
         * 是否在使用后就关闭
    14.  
         */
    15.  
        once?: boolean;
    16.  
       
    17.  
        /**
    18.  
         * 单独的样式名
    19.  
         */
    20.  
        className?: ClassName;
    21.  
       
    22.  
        /**
    23.  
         * 图标样式名
    24.  
         */
    25.  
        iconName?: ClassName;
    26.  
       
    27.  
        /**
    28.  
         * 函数
    29.  
         */
    30.  
        handler(): void;
    31.  
      }
    32.  
       
    33.  
      type RenderVNode = VNode<
    34.  
        RendererNode,
    35.  
        RendererElement,
    36.  
        {
    37.  
          [key: string]: any;
    38.  
        }
    39.  
      >;
    40.  
       
    41.  
      class CreateRightClick {
    42.  
        rightClickEl?: App<Element>;
    43.  
        rightClickElBox?: HTMLDivElement | null;
    44.  
       
    45.  
        constructor() {
    46.  
          this.removeRightClickHandler();
    47.  
        }
    48.  
       
    49.  
        /**
    50.  
         * 渲染dom
    51.  
         * @param menu
    52.  
         */
    53.  
        render(menu: MenuOptions[]): RenderVNode {
    54.  
          return h(
    55.  
            'ul',
    56.  
            {
    57.  
              class: ['right-click-menu-list']
    58.  
            },
    59.  
            [
    60.  
              ...menu.map(item => {
    61.  
                return h(
    62.  
                  'li',
    63.  
                  {
    64.  
                    class: item.className,
    65.  
                    // vue3.x中简化了render,直接onclick即可,onClick也可以
    66.  
                    onclick: () => {
    67.  
                      // 如果只是一次,那么点击之后直接关闭
    68.  
                      if (item.once) this.remove();
    69.  
                      return item.handler();
    70.  
                    }
    71.  
                  },
    72.  
                  [
    73.  
                    // icon
    74.  
                    h('i', {
    75.  
                      class: item.iconName
    76.  
                    }),
    77.  
                    // text
    78.  
                    h(
    79.  
                      'span',
    80.  
                      {
    81.  
                        class: 'right-click-menu-text'
    82.  
                      },
    83.  
                      item.text
    84.  
                    )
    85.  
                  ]
    86.  
                );
    87.  
              })
    88.  
            ]
    89.  
          );
    90.  
        }
    91.  
       
    92.  
        /**
    93.  
         * 给右键的样式
    94.  
         * @param event 鼠标事件
    95.  
         */
    96.  
        setRightClickElStyle(event: MouseEvent, len: number): void {
    97.  
          if (!this.rightClickElBox) return;
    98.  
          this.rightClickElBox.style.height = `${len * 36}px`;
    99.  
          const { clientX, clientY } = event;
    100.  
          const { innerWidth, innerHeight } = window;
    101.  
          const { clientWidth, clientHeight } = this.rightClickElBox;
    102.  
          let cssText = `height: ${len * 36}px;opacity: 1;transition: all 0.2s;`;
    103.  
          if (clientX + clientWidth < innerWidth) {
    104.  
            cssText += `left: ${clientX + 2}px;`;
    105.  
          } else {
    106.  
            cssText += `left: ${clientX - clientWidth}px;`;
    107.  
          }
    108.  
          if (clientY + clientHeight < innerHeight) {
    109.  
            cssText += `top: ${clientY + 2}px;`;
    110.  
          } else {
    111.  
            cssText += `top: ${clientY - clientHeight}px;`;
    112.  
          }
    113.  
          cssText += `height: ${len * 36}px`;
    114.  
          this.rightClickElBox.style.cssText = cssText;
    115.  
        }
    116.  
       
    117.  
        remove(): void {
    118.  
          if (this.rightClickElBox) {
    119.  
            this.rightClickElBox.remove();
    120.  
            this.rightClickElBox = null;
    121.  
          }
    122.  
        }
    123.  
       
    124.  
        removeRightClickHandler(): void {
    125.  
          document.addEventListener('click', e => {
    126.  
            if (this.rightClickElBox) {
    127.  
              const currentEl = e.target as Node;
    128.  
              if (!currentEl || !this.rightClickElBox.contains(currentEl)) {
    129.  
                this.remove();
    130.  
              }
    131.  
            }
    132.  
          });
    133.  
        }
    134.  
       
    135.  
        /**
    136.  
         * 鼠标右键悬浮
    137.  
         * @param event
    138.  
         * @param menu
    139.  
         */
    140.  
        useRightClick = (event: MouseEvent, menu: MenuOptions[] = []): void => {
    141.  
          this.remove();
    142.  
          if (!this.rightClickElBox || !this.rightClickEl) {
    143.  
            const createRender = this.render(menu);
    144.  
            this.rightClickEl = createApp({
    145.  
              setup() {
    146.  
                return () => createRender;
    147.  
              }
    148.  
            });
    149.  
          }
    150.  
          if (!this.rightClickElBox) {
    151.  
            this.rightClickElBox = document.createElement('div');
    152.  
            this.rightClickElBox.id = 'rightClick';
    153.  
            document.body.appendChild(this.rightClickElBox);
    154.  
            this.rightClickEl.mount('#rightClick');
    155.  
          }
    156.  
          this.setRightClickElStyle(event, menu.length);
    157.  
        };
    158.  
      }
    159.  
       
    160.  
      export default CreateRightClick; 

    右键弹窗插件配合electron打开、删除便笺笔记

    在使用的时候直接引入即可,如在index.vue中使用创建右键的方式,这里需要额外的说明一下,打开窗口需要进行一个窗口通信判断,ipcMain需要从remote中获取

    • 每个便笺笔记都有一个uid,也就是utils中生成的

    • 每个在打开笔记的时候也就是编辑页,需要判断该uid的窗口是否已经打开

    • 窗口之间用ipcRendereripcMain去通信

    • 判断通信失败的方法,用一个定时器来延时判断是否通信成功,因为没有判断通信失败的方法

    • countFlag = true就说明打开窗口,countFlag = false说明没有打开窗口

    ipcRendereripcMain通信

    ????on是一直处于通信状态,once是通信一次之后就关闭了

    1.  
      // countFlag是一个状态来标记收到东西没
    2.  
      // index问editor打开了没有
    3.  
      ipcRenderer.send('你好')
    4.  
       
    5.  
      // 这时候editor收到消息了
    6.  
      remote.ipcMain.on('你好', e => {
    7.  
        // 收到消息后显示
    8.  
        remote.getCurrentWindow().show();
    9.  
        // 然后回index消息
    10.  
        e.sender.send('你好我在的');
    11.  
      });
    12.  
       
    13.  
      // index在等editor消息
    14.  
      ipcRenderer.on('你好我在的', () => {
    15.  
        // 好的我收到了
    16.  
        countFlag = true;
    17.  
      });
    18.  
       
    19.  
      // 如果没收到消息,那标记一直是false,根据定时器来做相应操作 

    右键弹窗的使用

    ????这里的打开笔记功能会把选中的笔记uid当作一个query参数跳转到编辑页

    1.  
      import CreateRightClick from '@/components/rightClick';
    2.  
      ...
    3.  
      const rightClick = new CreateRightClick();
    4.  
      ...
    5.  
      const contextMenu = (event: MouseEvent, uid: string) => {
    6.  
        rightClick.useRightClick(event, [
    7.  
          {
    8.  
            text: '打开笔记',
    9.  
            once: true,
    10.  
            iconName: ['iconfont', 'icon-newopen'],
    11.  
            handler: () => {
    12.  
              let countFlag = false;
    13.  
              ipcRenderer.send(`${uid}_toOpen`);
    14.  
              ipcRenderer.on(`get_${uid}_toOpen`, () => {
    15.  
                countFlag = true;
    16.  
              });
    17.  
              setTimeout(() => {
    18.  
                if (!countFlag) openEditorWindow(uid);
    19.  
              }, 100);
    20.  
            }
    21.  
          },
    22.  
          {
    23.  
            text: '删除笔记',
    24.  
            once: true,
    25.  
            iconName: ['iconfont', 'icon-delete'],
    26.  
            handler: () => {
    27.  
              deleteCurrentUid.value = uid;
    28.  
              if (exeConfig.switchStatus.deleteTip) {
    29.  
                deleteMessageShow.value = true;
    30.  
              } else {
    31.  
                // 根据弹窗组件进行判断
    32.  
                onConfirm();
    33.  
              }
    34.  
            }
    35.  
          }
    36.  
        ]);
    37.  
      };
    38.  
      ... 

    editor.vue重点

    这个editor.vue是view/文件夹下的,以下对本页面统称编辑页,更好区分editor组件和页面 开发思路

    • 打开新增编辑页窗口时就生成uid并向数据库nedb添加数据,并向列表页通信ipcRenderer.send('createNewNote', res)

    • 需要使用富文本,能实时处理格式document.execCommand

    • 页面加载完时进行聚焦createRangegetSelection

    • 对列表页实时更新,编辑的时候防抖函数debounce可以控制输入更新,这个时间在设置是可控

    • 图钉固定header.vue已经说明

    • 选项功能能选择颜色,打开列表之后需要判断是否已经打开列表窗口

    • 点击关闭的时候需要删除数据库本条数据,如果没有输入内容就删除数据库uid内容并向列表页通信removeEmptyNoteItem

    • 在列表页时关闭本窗口的一个通信deleteActiveItem_{uid}

    • 列表页打开笔记时,携带uid,在编辑页根据是否携带uid查询该条数据库内容

    富文本编辑做成了一个单独的组件,使编辑页的代码不会太臃肿

    document.execCommand文档 developer.mozilla.org/zh-CN/docs/…[6]

    首先在编辑页对路由进行判断是否存在,如果不存在就创建,否则就查询并把查询到的笔记传给editor组件

    <Editor :content="editContent" :className="currentBgClassName" @on-input="changeEditContent" /> 
    
    1.  
      const routeUid = useRoute().query.uid as string;
    2.  
      if (routeUid) {
    3.  
        // 查询
    4.  
        uid.value = routeUid;
    5.  
        getCurUidItem(routeUid);
    6.  
      else {
    7.  
        // 生成uid并把uid放到地址栏
    8.  
        const uuidString = uuid();
    9.  
        uid.value = uuidString;
    10.  
        useRouter().push({
    11.  
          query: {
    12.  
            uid: uuidString
    13.  
          }
    14.  
        });
    15.  
        // 插入数据库并向列表页通信
    16.  
        ...
    17.  

    富文本聚焦和ref获取dom节点

    原理是通过getSelection选择光标和createRange文本范围两个方法,选中富文本节点。获取

    1.  
      import { defineComponent, onMounted, ref, Ref, watch } from 'vue';
    2.  
      ...
    3.  
      // setup中创建一个和<div ref="editor">同名的变量,就可以直接拿到dom节点,一定要return!!!
    4.  
      let editor: Ref<HTMLDivElement | null> = ref(null);
    5.  
       
    6.  
      onMounted(() => {
    7.  
        focus();
    8.  
      });
    9.  
       
    10.  
      const focus = () => {
    11.  
        const range = document.createRange();
    12.  
        range.selectNodeContents(editor.value as HTMLDivElement);
    13.  
        range.collapse(false);
    14.  
        const selecton = window.getSelection() as Selection;
    15.  
        selecton.removeAllRanges();
    16.  
        selecton.addRange(range);
    17.  
      };
    18.  
       
    19.  
      ...
    20.  
      return {
    21.  
        editor,
    22.  
        ...
    23.  

    editor组件的父传子以及watch监听

    ????这里需要注意的是因为在父组件传给子组件,然后子组件进行更新一次会导致富文本无法撤回,相当于重新给富文本组件赋值渲染了一次,因此这里就只用一次props.content

    1.  
      export default defineComponent({
    2.  
        props: {
    3.  
          content: String,
    4.  
          className: String
    5.  
        },
    6.  
        emits: ['on-input'],
    7.  
        setup(props, { emit }) {
    8.  
          let editor: Ref<HTMLDivElement | null> = ref(null);
    9.  
          const bottomIcons = editorIcons;
    10.  
          const editorContent: Ref<string | undefined> = ref('');
    11.  
       
    12.  
          // 监听从父组件传来的内容,因为是从数据库查询所以会有一定的延迟
    13.  
          watch(props, nv => {
    14.  
            if (!editorContent.value) {
    15.  
              // 只赋值一次
    16.  
              editorContent.value = nv.content;
    17.  
            }
    18.  
          });
    19.  
        }
    20.  
      }); 

    editor组件的防抖子传父

    exeConfig.syncDelay是设置里面的一个时间,可以动态根据这个时间来调节储存进数据库和列表的更新,获取富文本组件的html然后储存到数据库并传到列表页更新

    1.  
      const changeEditorContent = debounce((e: InputEvent) => {
    2.  
        const editorHtml = (e.target as Element).innerHTML;
    3.  
        emit('on-input', editorHtml);
    4.  
      }, exeConfig.syncDelay); 

    富文本组件的粘贴纯文本

    vue自带的粘贴事件,@paste获取到剪切板的内容,然后获取文本格式的内容e.clipboardData?.getData('text/plain')并插入富文本

    1.  
      const paste = (e: ClipboardEvent) => {
    2.  
        const pasteText = e.clipboardData?.getData('text/plain');
    3.  
        console.log(pasteText);
    4.  
        document.execCommand('insertText', false, pasteText);
    5.  
      }; 

    (????????????额外的)getCurrentInstance选择dom方式

    官方和网上的例子是这样:

    <div ref="editor"></div> 
    
    1.  
      setup(props, { emit }) {
    2.  
        let editor = ref(null);
    3.  
        return { editor }
    4.  
      }) 

    直接获取dom节点,但其实不管这个editor是什么,只要从setupreturn,就会直接标记instance变量名,强行把内容替换成dom节点,甚至不用定义可以看看下面例子

    <div ref="test"></div> 
    
    1.  
      import { defineComponent, getCurrentInstance, onMounted } from 'vue';
    2.  
      ...
    3.  
      setup(props, { emit }) {
    4.  
        onMounted(() => {
    5.  
          console.log(getCurrentInstance().refs);
    6.  
          // 得到的是test dom以及其他定义的节点
    7.  
        });
    8.  
        return {
    9.  
          test: ''
    10.  
        }
    11.  
      }) 

    但是为了规范还是使用下面这样

    <div ref="dom"></div> 
    
    1.  
      const dom = ref(null);
    2.  
      return {
    3.  
        dom
    4.  
      }; 

    setting.vue

    这里的话需要用到exeConfig.state.ts的配置信息,包括封装的inputswitchtick组件

    在这里说明一下,自动缩小靠边隐藏同步设置暂时还没有开发的

    • 自动缩小: 编辑页失去焦点时自动最小化,获得焦点重新打开

    • 靠边隐藏: 把软件拖动到屏幕边缘时,自动隐藏到边上,类似QQ那样的功能

    • 同步设置: 打算使用nestjs做同步服务,后面可能会出一篇有关的文章,但是功能一定会做的

    directives自定义指令

    根据是否开启提示的设置写的一个方便控制的功能,这个功能是首先获取初始化的节点高度,放置在dom的自定义数据上面data-xx,然后下次显示的时候再重新获取赋值css显示,当然这里也是用了一个过渡效果

    使用方法

    <div v-tip="switch"></div> 
    
    1.  
      export default defineComponent({
    2.  
        components: {
    3.  
          Tick,
    4.  
          Input,
    5.  
          Switch
    6.  
        },
    7.  
        directives: {
    8.  
          tip(el, { value }) {
    9.  
            const { height } = el.dataset;
    10.  
            // 储存最初的高度
    11.  
            if (!height && height !== '0') {
    12.  
              el.dataset.height = el.clientHeight;
    13.  
            }
    14.  
            const clientHeight = height || el.clientHeight;
    15.  
            let cssText = 'transition: all 0.4s;';
    16.  
            if (value) {
    17.  
              cssText += `height: ${clientHeight}px;opacity: 1;`;
    18.  
            } else {
    19.  
              cssText += 'height: 0;opacity: 0;overflow: hidden;';
    20.  
            }
    21.  
            el.style.cssText = cssText;
    22.  
          }
    23.  
        }
    24.  
      }) 

    原生点击复制

    原理是先隐藏一个input标签,然后点击的之后选择它的内容,在使用document.execCommand('copy')复制就可以

    1.  
      <a @click="copyEmail">复制</a>
    2.  
      <input class="hide-input" ref="mailInput" type="text" value="heiyehk@foxmail.com" /> 
    1.  
      const mailInput: Ref<HTMLInputElement | null> = ref(null);
    2.  
      const copyEmail = () => {
    3.  
        if (copyStatus.value) return;
    4.  
        copyStatus.value = true;
    5.  
        mailInput.value?.select();
    6.  
        document.execCommand('copy');
    7.  
      };
    8.  
       
    9.  
      return {
    10.  
        copyEmail
    11.  
        ...
    12.  

    electron打开文件夹和打开默认浏览器链接

    打开文件夹使用shell这个方法

    1.  
      import { remote } from 'electron';
    2.  
       
    3.  
      remote.shell.showItemInFolder('D:'); 

    打开默认浏览器链接

    1.  
      import { remote } from 'electron';
    2.  
       
    3.  
      remote.shell.openExternal('www.github.com'); 

    错误收集

    收集一些使用中的错误,并使用message插件进行弹窗提示,软件宽高和屏幕宽高只是辅助信息。碰到这些错误之后,在软件安装位置输出一个inoteError.log的错误日志文件,然后在设置中判断文件是否存在,存在就打开目录选中。

    • 版本号

    • 时间

    • 错误

    • electron版本

    • Windows信息

    • 软件宽高信息

    • 屏幕宽高

    比如这个框中的才是主要的信息

    vue3 errorHandler

    main.ts我们需要进行一下改造,并使用errorHandler进行全局的错误监控

    1.  
      import { createApp } from 'vue';
    2.  
      import App from './App.vue';
    3.  
      import router from './router';
    4.  
      import outputErrorLog from '@/utils/errorLog';
    5.  
       
    6.  
      const app = createApp(App);
    7.  
       
    8.  
      // 错误收集方法
    9.  
      app.config.errorHandler = outputErrorLog;
    10.  
       
    11.  
      app.use(router).mount('#app'); 

    errorLog.ts封装对Error类型输出为日志文件

    获取软件安装位置

    remote.app.getPath('exe')获取软件安装路径,包含软件名.exe

    export const errorLogPath = path.join(remote.app.getPath('exe'), '../inoteError.log'); 
    

    输出日志文件

    flag: a代表末尾追加,确保每一行一个错误加上换行符' '

    fs.writeFileSync(errorLogPath, JSON.stringify(errorLog) + '
    ', { flag: 'a' }); 
    

    errorLog.ts的封装,对Error类型的封装

    1.  
      import { ComponentPublicInstance } from 'vue';
    2.  
      import dayjs from 'dayjs';
    3.  
      import fs from 'fs-extra';
    4.  
      import os from 'os';
    5.  
      import { remote } from 'electron';
    6.  
      import path from 'path';
    7.  
      import useMessage from '@/components/message';
    8.  
       
    9.  
      function getShortStack(stack?: string): string {
    10.  
        const splitStack = stack?.split('     ');
    11.  
        if (!splitStack) return '';
    12.  
        const newStack: string[] = [];
    13.  
        for (const line of splitStack) {
    14.  
          // 其他信息
    15.  
          if (line.includes('bundler')) continue;
    16.  
       
    17.  
          // 只保留错误文件信息
    18.  
          if (line.includes('?!.')) {
    19.  
            newStack.push(line.replace(/webpack-internal:///./node_modules/.+?!/, ''));
    20.  
          } else {
    21.  
            newStack.push(line);
    22.  
          }
    23.  
        }
    24.  
        // 转换string
    25.  
        return newStack.join('     ');
    26.  
      }
    27.  
       
    28.  
      export const errorLogPath = path.join(remote.app.getPath('exe'), '../inoteError.log');
    29.  
       
    30.  
      export default function(error: unknown, vm: ComponentPublicInstance | null, info: string): void {
    31.  
        const { message, stack } = error as Error;
    32.  
        const { electron, chrome, node, v8 } = process.versions;
    33.  
        const { outerWidth, outerHeight, innerWidth, innerHeight } = window;
    34.  
        const { width, height } = window.screen;
    35.  
       
    36.  
        // 报错信息
    37.  
        const errorInfo = {
    38.  
          errorInfo: info,
    39.  
          errorMessage: message,
    40.  
          errorStack: getShortStack(stack)
    41.  
        };
    42.  
       
    43.  
        // electron
    44.  
        const electronInfo = { electron, chrome, node, v8 };
    45.  
       
    46.  
        // 浏览器窗口信息
    47.  
        const browserInfo = { outerWidth, outerHeight, innerWidth, innerHeight };
    48.  
       
    49.  
        const errorLog = {
    50.  
          versions: remote.app.getVersion(),
    51.  
          date: dayjs().format('YYYY-MM-DD HH:mm'),
    52.  
          error: errorInfo,
    53.  
          electron: electronInfo,
    54.  
          window: {
    55.  
            type: os.type(),
    56.  
            platform: os.platform()
    57.  
          },
    58.  
          browser: browserInfo,
    59.  
          screen: { width, height }
    60.  
        };
    61.  
       
    62.  
        useMessage('程序出现异常', 'error');
    63.  
       
    64.  
        if (process.env.NODE_ENV === 'production') {
    65.  
          fs.writeFileSync(errorLogPath, JSON.stringify(errorLog) + ' ', { flag: 'a' });
    66.  
        } else {
    67.  
          console.log(error);
    68.  
          console.log(errorInfo.errorStack);
    69.  
        }
    70.  

    使用此方法后封装的结果是这样的,message插件具体看component

    这个是之前的错误日志文件

    获取electron版本等信息

    const appInfo = process.versions; 
    

    打包

    这个倒是没什么好讲的了,主要还是在vue.config.js文件中进行配置一下,然后使用命令yarn electron:build即可,当然了,还有一个打包前清空的旧的打包文件夹的脚本

    deleteBuild.js

    打包清空dist_electron旧的打包内容,因为eslint的原因,这里就用eslint-disable关掉了几个

    原理就是先获取vue.config.js中的打包配置,如果重新配置了路径directories.output就动态去清空

    1.  
      const rm = require('rimraf');
    2.  
      const path = require('path');
    3.  
      const pluginOptions = require('../../vue.config').pluginOptions;
    4.  
       
    5.  
      let directories = pluginOptions.electronBuilder.builderOptions.directories;
    6.  
      let buildPath = '';
    7.  
       
    8.  
      if (directories && directories.output) {
    9.  
        buildPath = directories.output;
    10.  
      }
    11.  
       
    12.  
      // 删除作用只用于删除打包前的buildPath || dist_electron
    13.  
      // dist_electron是默认打包文件夹
    14.  
      rm(path.join(__dirname, `../../${buildPath || 'dist_electron'}`), () => {}); 

    以上就是本篇主要开发内容了,欢迎支持我的开源项目electron-vue3-inote。

    相关资料

    github地址: https://github.com/heiyehk/electron-vue3-inote

    文章参考:  https://juejin.cn/post/6909723449246089224

    ❤️ 看完三件事

    如果你觉得这篇内容对你挺有启发,我想邀请你帮我三个小忙:

    • 点个【在看】,或者分享转发,让更多的人也能看到这篇内容

    • 关注公众号【趣谈前端】,定期分享 工程化 / 可视化 / 低代码 / 优秀开源。

    从零搭建全栈可视化大屏制作平台V6.Dooring

    从零设计可视化大屏搭建引擎

    Dooring可视化搭建平台数据源设计剖析

    可视化搭建的一些思考和实践

    基于Koa + React + TS从零开发全栈文档编辑器(进阶实战

原文地址:https://www.cnblogs.com/onesea/p/15512233.html