1.electron架構思考
在做electron桌面開發中,Electron+vue當下算是性價比的比較高的。但是electron算是小眾開發,遇到問題,基本上就是掉進深坑,爬好久才出來。
為了做一個項目,我翻遍了國內好多網站。看到一篇好的文章。Electron 應用實戰 (架構篇) 這篇還是很值得好好看看
其中一句話,我覺得講的很有道理====》數據通訊方案決定整體的架構方案。
原因:Electron 有兩個進程,分別為 main 和 renderer,而兩者之間需要進行通訊,通訊機制不同。
1. 方案1 只是簡單的通信,沒有大數據量通信。
通常采用本身的自帶方案,ipc方式 main 端有 ipcMain,renderer 端有 ipcRenderer,分別用於通訊。
缺點:不支持大數據通信和復雜的業務邏輯
2.用remote模塊渲染進程直接調用主進程的進程
remote模塊官方文檔 https://electronjs.org/docs/api/remote
例如
主進程:
// 主進程 mapNumbers.js exports.withRendererCallback = (mapper) => { return [1, 2, 3].map(mapper) } exports.withLocalCallback = () => { return [1, 2, 3].map(x => x + 1) }
渲染進程
// 渲染進程 const mapNumbers = require('electron').remote.require('./mapNumbers') const withRendererCb = mapNumbers.withRendererCallback(x => x + 1) const withLocalCb = mapNumbers.withLocalCallback() console.log(withRendererCb, withLocalCb) // [undefined, undefined, undefined], [2, 3, 4]
3.Electron+vue一渲染進程直接調用主進程的方法
3.1創建項目
vue init simulatedgreg/electron-vue my-project
3.2安裝依賴
npm install
3.3產生目錄結構
project/ ├── main │ ├── foo.js │ └── index.js └── renderer └── main.js
└── components
└── landingPage.vue
└── .electron-vue
└── webpack.main.config.js
3.4主進程=>創建 foo.js
module.exports = { getTest1(){ return 'test1'; }, getTest2(){ return 'test2'; }, }
3.4渲染進程=>main.js
import Vue from 'vue' import axios from 'axios' import App from './App' import router from './router' import store from './store' //引入foo主進程 const foo = require('electron').remote.require('./foo'); //將 foo 掛載到 vue 的原型上 Vue.prototype.foo = foo;
3.5 landingPage.vue
<script> export default { methods: { clickMethodInMainProcess() { console.log('\n\n------ begin: ------') console.log(this.foo.getTest1()) console.log(this.foo.getTest2()) console.log('------ end: ------\n\n') } } </script>el
3.6 webpack增加新entry
在 .electron-vue/webpack.main.config.js 添加新entry
a good solution by editing the webpack.main.config.js
and manually adding every relative module as new entries.
let mainConfig = { entry: { main: path.join(__dirname, '../src/main/index.js'), foo: path.join(__dirname, '../src/main/foo.js') }, }
參考:
https://github.com/SimulatedGREG/electron-vue/issues/291