网上找了很多资料,很多没头没尾的,最终根据多个资料理解整合了下,经过测试没问题,一套下来处理下来,你只要多去翻看electron的使用就可以了愉快的在vue中调用electron的API了
准备工作
#1.创建vue项目
vue create your-project
#2.
#这里要多一个步骤,不然 add electron-builder的时候可能会报错
npm config edit #增加三个源
#添加下面三个配置
#disturl=https://registry.npmmirror.com/-/binary/node
#electron_mirror=https://registry.npmmirror.com/-/binary/electron/
#registry=https://registry.npmmirror.com
#安装electron-builder打包插件,这里会自动安装electron
vue add electron-builder
修改background.js
找到
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
}
})
修改为
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,
nodeIntegration: true,//这里修改
enableRemoteModule: true,//这里添加
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
修改vue.config.js
修改前
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
})
修改后
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
pluginOptions: {
electronBuilder: {
nodeIntegration: true
}
}
})
使用electronAPI
方法一
App.vue中直接使用
const electron = require('electron')
console.log(electron.remote.app.getName())
图就见方法二的使用中把
方法二
新建scr/plugins/VueElectron.js
const electron = require('electron')
module.exports = {
install: function (Vue) {
Object.defineProperties(Vue.prototype, {
$electron: {
get () {
return electron
},
},
})
},
}
在main.js中引用VueElectron.js
import VueElectron from '@/plugins/VueElectron'
Vue.use(VueElectron)
App.vue中使用
export default {
created () {
console.log(this.getName())
},
methods: {
getName () {
return this.$electron.remote.app.getName()
}
}
}