electron-vue 中使用Electron Api和nodejs以及主进程渲染通信
app.vue
<template> <div id="app"> <div class="header"> <router-link to='home'>首页</router-link> <router-link to='news'>新闻</router-link> </div> <router-view></router-view> </div> </template> <script> export default { name: 'electronvuedemo' } </script> <style> /* CSS */ .header{ height: 44px; line-height: 44px; text-align: center; background: #000; } .header a{ color: #fff; } </style>
router/index.js
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router); import Home from '@/components/Home.vue'; import News from '@/components/News.vue'; export default new Router({ routes: [ { path: '/', name: 'home', component:Home }, { path: '/news', name: 'news', component: News }, { path: '*', redirect: '/' } ] })
home.vue
<template> <div id="home"> {{msg}} <br> <br> <button @click="sendMsg()">给主进程广播数据</button> <br> <br> <!-- click.stop 阻止冒泡 click.prevent 阻止默认行为 --> <a href="http://www.baidu.com" @click.prevent="openUrl($event)">打开百度</a> <br> <br> <button @click="runNode()">使用nodejs的模块</button> </div> </template> <script> var path=require('path'); export default{ data(){ return { msg:'首页组件' } }, methods:{ sendMsg(){ alert('执行') this.$electron.ipcRenderer.send('toMain','我是渲染进程里面的数据') }, openUrl(event){ console.log(event.srcElement.href) var linkUrl=event.srcElement.href; this.$electron.shell.openExternal(linkUrl); }, runNode(){ var dir=path.join('/aaaa','xxxx'); console.log(dir); } } } </script>
news.vue
<template> <div id="news"> 新闻组件 <br> <button @click="runNode()">使用nodejs的fs模块</button> </div> </template> <script> var fs=require('fs'); export default{ data(){ return { msg:'我是新闻页面' } }, methods:{ runNode(){ fs.readFile('package.json',(err,data)=>{ if(err){ console.log(err); return; } console.log(data.toString()); }) } } } </script>
main/icpMain.js
var {ipcMain}=require('electron'); //接收渲染进程广播的数据 ipcMain.on('toMain',(event,data)=>{ console.log('1111') console.log(data); })
运行:
npm run dev
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
posted on 2021-01-11 11:29 LoaderMan 阅读(2696) 评论(0) 编辑 收藏 举报