简单粗暴、踩坑指南:vue内使用electron内的API,如CMD命令、更新等

网上找了很多资料,很多没头没尾的,最终根据多个资料理解整合了下,经过测试没问题,一套下来处理下来,你只要多去翻看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()
    }
  }
}

效果

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值