1. 程式人生 > >Electron+vue-應用實戰 - 深坑之一渲染程序直接呼叫主程序

Electron+vue-應用實戰 - 深坑之一渲染程序直接呼叫主程序

1.electron架構思考

在做electron桌面開發中,Electron+vue當下算是價效比的比較高的。但是electron算是小眾開發,遇到問題,基本上就是掉進深坑,爬好久才出來。

為了做一個小專案,我翻遍了國內好多網站。看到一篇好的文章。Electron 應用實戰 (架構篇) 這篇還是很值得好好看看

其中一句話,我覺得講的很有道理====》資料通訊方案決定整體的架構方案。

原因:Electron 有兩個程序,分別為 main 和 renderer,而兩者之間需要進行通訊,通訊機制不同。

1. 方案1只是簡單的通訊,沒有大資料量通訊。

通常採用本身的自帶方案,=》ipc方式main 端有 ipcMain,renderer 端有 ipcRenderer,分別用於通訊。

缺點:不支援大資料通訊和複雜的業務邏輯

2. 方案2 :包含業務大量邏輯,並且有大資料量通訊

官方:用remote模組  https://electronjs.org/docs/api/remote

缺點:適合electron專案。不適合Electron+vue官方(vue init simulatedgreg/electron-vue my-project)

3. 方案3 :包含業務大量邏輯,並且有大資料量通訊

修改webpack

適合Electron+vue官方(vue init simulatedgreg/electron-vue my-project)

2.用remote模組 

深坑=》渲染程序直接呼叫主程序的程序

用remote模組  =>https://electronjs.org/docs/api/remote

主程序中的程式碼可以接受來自渲染程序的回撥 - 例如remote模組 

首先,為了避免死鎖,傳遞給主程序的回撥被非同步呼叫。 您不應該期望主程序獲得傳遞迴調的返回值。

例如,您不能在主程序中呼叫的Array.map中使用來自渲染器程序的函式:

// 主程序 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

安裝依賴

npm install

產生目錄結構

project/
├── main
│   ├── foo.js
│   └── index.js
└── renderer
    └── main.js

主程序=>建立 foo.js

module.exports = {
    getTest1(){
        return 'test1';
    },
    getTest2(){
        return 'test2';
    },

    }  

 

渲染程序=>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;

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

webpack修改

 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