基於vue3+electron11跨端仿制QQ桌面應用實戰Vue3ElectronQchat。
使用vue3+electron+vuex4+ant-design-vue+v3scroll+v3layer等技術構建跨平台模仿QQ|TIM界面聊天應用。實現了發送富文本消息、圖片/視頻/鏈接預覽、拖拽發送圖片、調用dll截圖、朋友圈等功能。支持多開窗口|父子modal窗口、換膚等操作。
一、技術棧
- 編碼工具:vscode
- 框架技術:vue3.0+electron11.2.3+vuex4+vue-router@4
- 組件庫:ant-design-vue^2.0.0 (螞蟻金服pc端vue3組件庫)
- 打包工具:vue-cli-plugin-electron-builder
- 按需引入:babel-plugin-import^1.13.3
- 彈窗組件:v3layer(基於vue3封裝的自定義對話框組件)
- 滾動條組件:v3scroll(基於vue3封裝的美化系統滾動條)
- 矢量圖標:阿里iconfont字體圖標庫
二、目錄結構
◆ 一睹效果
◆ electron實現新開窗口/多窗體並存
項目支持新開多個窗口,只需調用公共createWin方法並傳入配置參數即可快速新開一個窗口。
// 關於窗口 const handleAboutWin = () => { createWin({ title: '關於', route: '/about', width: 380, height: 280, resize: false, parent: winCfg.window.id, modal: true, }) } // 換膚窗口 const handleSkinWin = () => { createWin({ title: '換膚', route: '/skin', width: 720, height: 475, resize: false, }) } // 朋友圈窗口 const handleFZoneWin = () => { createWin({ title: '朋友圈', route: '/fzone', width: 550, height: 700, resize: false, }) } // 界面管理器窗口 const handleUIManager = () => { createWin({ title: '界面管理器', route: '/uimanager', width: 400, height: 475, resize: false, parent: winCfg.window.id, modal: true, }) }
支持如下參數配置:
// 窗口參數配置 export const winConfig = { id: null, // 窗口唯一id background: '#fff', // 背景色 route: '', // 路由地址url title: '', // 標題 data: null, // 傳入數據參數 width: '', // 窗口寬度 height: '', // 窗口高度 minWidth: '', // 窗口最小寬度 minHeight: '', // 窗口最小高度 x: '', // 窗口相對於屏幕左側坐標 y: '', // 窗口相對於屏幕頂端坐標 resize: true, // 是否支持縮放 maximize: false, // 最大化窗口 isMultiWin: false, // 是否支持多開窗口(為true則會支持創建多個窗口) isMainWin: false, // 是否主窗口(為true則會替代之前主窗口) parent: '', // 父窗口(傳入父窗口id) modal: false, // 模態窗口(需設置parent和modal選項) alwaysOnTop: false, // 是否置頂窗口 }
至於如何使用vue3+electron搭建項目和創建多窗口,之前有過一篇分享文章,大家可以去看看。
https://www.cnblogs.com/xiaoyan2017/p/14403820.html
◆ electron自定義無邊框窗體拖拽/禁用系統右鍵菜單
項目采用無邊框模式 frame: false 如上圖所示區域是自定義拖拽導航欄。支持傳入標題、標題顏色/背景色、是否透明背景等功能。
但有一個問題,設置 -webkit-app-region: drag 之后,點擊鼠標右鍵會彈出系統菜單,總感覺是一種偽拖拽效果,可通過如下方法在創建窗體的時候暫時給屏蔽掉。
// 屏蔽系統右鍵菜單 win.hookWindowMessage(278, () => { win.setEnabled(false) setTimeout(() => { win.setEnabled(true) }, 100) return true })
至於如何自定義導航條及最大化/最小化/關閉按鈕,之前也有過一篇分享文章,大家感興趣可以去看一看。
https://www.cnblogs.com/xiaoyan2017/p/14449570.html
◆ electron實現QQ托盤圖標/閃爍
關閉主窗體的時候,會提示直接關閉軟件還是最小化到系統托盤。
// 關閉窗口 const handleWinClose = () => { if(winCfg.window.isMainWin) { let $el = v3layer({ type: 'android', content: '是否最小化至托盤,不退出程序?', btns: [ { text: '殘忍退出', style: 'color:#ff5438', click: () => { $el.close() store.commit('LOGOUT') setWin('close') } }, { text: '最小化至托盤', style: 'color:#00d2ff', click: () => { $el.close() win.hide() } } ] }) }else { setWin('close', winCfg.window.id) } }
由於項目支持打開多個窗口,在關閉的時候需要判斷是否是主窗口,如果不是則直接傳入該窗口id進行關閉,如果是主窗口,則會出現彈窗提示。
// 創建系統托盤圖標 let tray = null let flashTimer = null let trayIco1 = path.join(__dirname, '../static/tray.ico') let trayIco2 = path.join(__dirname, '../static/tray-empty.ico') createTray() { const trayMenu = Menu.buildFromTemplate([ { label: '我在線上', icon: path.join(__dirname, '../static/icon-online.png'), click: () => {...} }, { label: '忙碌', icon: path.join(__dirname, '../static/icon-busy.png'), click: () => {...} }, { label: '隱身', icon: path.join(__dirname, '../static/icon-invisible.png'), click: () => {...} }, { label: '離開', icon: path.join(__dirname, '../static/icon-offline.png'), click: () => {...} }, {type: 'separator'}, { label: '關閉所有聲音', click: () => {...}, }, { label: '關閉頭像閃動', click: () => { this.flashTray(false) } }, {type: 'separator'}, { label: '打開主窗口', click: () => { try { for(let i in this.winLs) { let win = this.getWin(i) if(!win) return if(win.isMinimized()) win.restore() win.show() } } catch (error) { console.log(error) } } }, { label: '退出', click: () => { try { for(let i in this.winLs) { let win = this.getWin(i) if(win) win.webContents.send('win-logout') } app.quit() } catch (error) { console.log(error) } } }, ]) this.tray = new Tray(this.trayIco1) this.tray.setContextMenu(trayMenu) this.tray.setToolTip(app.name) this.tray.on('double-click', () => { // ... }) } // 托盤圖標閃爍 flashTray(flash) { let hasIco = false if(flash) { if(this.flashTimer) return this.flashTimer = setInterval(() => { this.tray.setImage(hasIco ? this.trayIco1 : this.trayIco2) hasIco = !hasIco }, 500) }else { if(this.flashTimer) { clearInterval(this.flashTimer) this.flashTimer = null } this.tray.setImage(this.trayIco1) } } // 銷毀托盤圖標 destoryTray() { this.flashTray(false) this.tray.destroy() this.tray = null }
大家需要准備兩個大小一樣的ico圖標,其中一個透明即可。通過定時器控制 setImage() 函數來顯示ico圖標,達到閃爍效果。
通過調用 flashTray(true|false) 方法來開啟/停止托盤閃爍。
注意:圖標路徑如果不正確,則無法顯示托盤圖標,大家可以 console.log(__dirname) 來查看路徑。默認是輸出dist_electron目錄。
◆ vue3.0全局對話框/虛擬滾動條組件
大家看到的項目中有一些彈窗是使用vue3自定義組件來實現的。另外項目中的滾動條也是使用vue3自定義封裝替代系統滾動條。
之前也有過兩篇相關的技術分享,這里就不詳細介紹了,大家感興趣也可以去看看哈。
https://www.cnblogs.com/xiaoyan2017/p/14221729.html
https://www.cnblogs.com/xiaoyan2017/p/14242983.html
◆ vue3.x+electron項目配置/打包配置
項目搭建之后,根目錄會有一個vue.config.js項目配置文件。可進行一些簡單的環境/插件配置,另外electron-builder打包參數也可以在里面進行配置。
/** * @Desc vue3項目配置文件 * @Time andy by 2021-02 * @About Q:282310962 wx:xy190310 */ const path = require('path') module.exports = { // 基本路徑 // publicPath: '/', // 輸出文件目錄 // outputDir: 'dist', // assetsDir: '', // 環境配置 devServer: { // host: 'localhost', // port: 8080, // 是否開啟https https: false, // 編譯完是否打開網頁 open: false, // 代理配置 // proxy: { // '^/api': { // target: '<url>', // ws: true, // changeOrigin: true // }, // '^/foo': { // target: '<other_url>' // } // } }, // webpack配置 chainWebpack: config => { // 配置路徑別名 config.resolve.alias .set('@', path.join(__dirname, 'src')) .set('@assets', path.join(__dirname, 'src/assets')) .set('@components', path.join(__dirname, 'src/components')) .set('@module', path.join(__dirname, 'src/module')) .set('@plugins', path.join(__dirname, 'src/plugins')) .set('@layouts', path.join(__dirname, 'src/layouts')) .set('@views', path.join(__dirname, 'src/views')) }, // 插件配置 pluginOptions: { electronBuilder: { // 配置后可以在渲染進程使用ipcRenderer nodeIntegration: true, // 項目打包參數配置 builderOptions: { "productName": "electron-qchat", //項目名稱 打包生成exe的前綴名 "appId": "com.example.electronqchat", //包名 "compression": "maximum", //store|normal|maximum 打包壓縮情況(store速度較快) "artifactName": "${productName}-${version}-${platform}-${arch}.${ext}", //打包后安裝包名稱 // "directories": { // "output": "build", //輸出文件夾(默認dist_electron) // }, "asar": false, //asar打包 // 拷貝靜態資源目錄到指定位置 "extraResources": [ { "from": "./static", "to": "static" }, ], "nsis": { "oneClick": false, //一鍵安裝 "allowToChangeInstallationDirectory": true, //允許修改安裝目錄 "perMachine": true, //是否開啟安裝時權限設置(此電腦或當前用戶) "artifactName": "${productName}-${version}-${platform}-${arch}-setup.${ext}", //打包后安裝包名稱 "deleteAppDataOnUninstall": true, //卸載時刪除數據 "createDesktopShortcut": true, //創建桌面圖標 "createStartMenuShortcut": true, //創建開始菜單圖標 "shortcutName": "ElectronQChat", //桌面快捷鍵圖標名稱 }, "win": { "icon": "./static/shortcut.ico", //圖標路徑 } } } } }
◆ ant-design-vue組件庫按需引入
有時候項目開發,需要用到一些組件庫里面的個別功能,這時按需引入最適合,會減少打包后的大小。
安裝按需引入插件 npm i babel-plugin-import -D 並在babel.config.js里面進行相關引入配置。
module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ], // 按需引入第三方插件 plugins: [ [ 'import', { 'libraryName': 'ant-design-vue', 'libraryDirectory': 'es', 'style': 'css', } ] ] }
這時候就可以按需引入ant-design-vue組件了,樣式文件會自動引入的。
// 按需引入ant-design-vue組件庫 import { Button, message, Tabs, Checkbox, Image, Upload } from 'ant-design-vue' // ... const Plugins = (app) => { app.use(Button) app.use(Tabs) app.use(Checkbox) app.use(Image) app.use(Upload) // ... app.config.globalProperties.$message = message } export default Plugins
◆ electron實現截圖功能
項目中的截圖功能,本想着自己搗鼓一個,后來時間有限,就使用了一個微信截圖dll來實現。可實現基本功能,並且打包后也可以截圖。
// 屏幕截圖 ipcMain.on('win-capture', () => { console.log('調用微信dll截圖...') let printScr = execFile(path.join(__dirname, '../static/screenShot/PrintScr.exe')) printScr.on('exit', (code) => { if(code) { console.log(code) } }) })
如果出現打包后,截圖功能失效,需要在vue.config.js的打包配置中添加 extraResources 字段配置。
// 拷貝靜態資源目錄到指定位置 "extraResources": [ { "from": "./static", "to": "static" }, ],
from表示文件原路徑,to表示打包后資源放置的路徑。打包之后會在resources目錄下有個static目錄。
另外還需注意:
1、項目路徑不能含有中文,否則打包會出錯!
2、盡量不要使用 getCurrentInstance 函數來操作store或router,打包也會出錯!
3、在渲染進程,也就是.vue頁面,使用ipcRenderer或remote出現如下錯誤
Uncaught TypeError: fs.existsSync is not a function
則需要配置 nodeIntegration: true 來開啟Node環境支持。
OK,基於Vue3+Electron開發桌面端仿Q應用就分享到這里。希望對大家有所幫助哈~~ 👽😎
最后附上一個vite2+vue3+vant3短視頻實例項目
https://www.cnblogs.com/xiaoyan2017/p/14361160.html