使用vue-cli4 + element-plus + electron构建跨平台应用


1.安装脚手架vue-cli4;

   安装脚手架

npm install -g @vue/cli

   安装项目

vue create 项目名称

    配置项目

  Default ([Vue 2] babel, eslint) 
  Default (Vue 3 Preview) ([Vue 3] babel, eslint) 
❯ Manually select features

? Check the features needed for your project: 
 ◉ Choose Vue version
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
❯◉ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing 

2.引入element-plus组件;

yarn add element-plus -S

3.引入electron到脚手架项目;

vue add electron-builder

  选择最新的electron版本

? Choose Electron Version (Use arrow keys)
  ^10.0.0 
  ^11.0.0 
❯ ^12.0.0 

  配置vue.config.js,优化构建项目

const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')

const path = require('path')
const resolve = dir => path.join(__dirname, dir)

module.exports = {
  configureWebpack: {
    plugins: [
      // 对element-plus组件进行tree-shaking配置
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      // 对element-plus组件进行tree-shaking配置
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    resolve: {
      // 设置快捷路径, @ 表示 'src' ,components 表示 'src/components'
      alias: {
        '@': resolve('src'),
        assets: resolve('src/assets'),
        components: resolve('src/components'),
        views: resolve('src/views')
      }
    }
  },
  pluginOptions: {
    electronBuilder: {
      builderOptions: {
        win: {
          icon: './src/assets/logo.ico'
        },
        mac: {
          icon: './src/assets/logo.icns'
        },
        productName: 'GG文档'
      }
    }
  }
}

  根据项目需要配置background.js

'use strict'

import { app, protocol, BrowserWindow, Menu, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow () {
  // 获取屏幕尺寸
  const size = screen.getPrimaryDisplay().workAreaSize
  const width = parseInt(size.width * 0.9)
  const height = parseInt(size.height * 0.9)
  // Create the browser window.
  const win = new BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    },
    icon: 'src/assets/img/logo.ico'
    // titleBarStyle: 'hidden'
  })

  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)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  createMenu()
}

// 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()
})

// 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()
    })
  }
}

// 设置菜单栏
function createMenu () {
  // darwin表示macOS,针对macOS的设置
  if (process.platform === 'darwin') {
    const template = [{
      label: 'App Demo',
      submenu: [
        { role: 'about' },
        {
          role: 'quit'
        }]
    }]
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    // windows及linux系统
    Menu.setApplicationMenu(null)
  }
}

  main.js配置

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import i18n from 'assets/lang/index.js'

createApp(App).use(ElementPlus).use(i18n).use(store).use(router).mount('#app')

  国际化配置

/* eslint-disable camelcase */
import { createI18n } from 'vue-i18n'
import el_en from 'element-plus/es/locale/lang/en'
import el_zh from 'element-plus/es/locale/lang/zh-cn'
import zh from '@/assets/lang/zh'
import en from '@/assets/lang/en'
import Storage from '@/utils/storage.js'

const i18n = createI18n({
  locale: Storage.localGet('locale') || 'zh-CN', // 语言标识, 通过切换locale的值来实现语言切换,this.$i18n.locale
  messages: {
    'zh-CN': Object.assign({ lang: zh }, el_zh), // 中文语言包
    'en-US': Object.assign({ lang: en }, el_en) // 英文语言包
  }
})

export default i18n

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM