简单看了一下electron的api,然后用忘了一半的node和学了一半的ES6开始写-_-|||。主要记录一些坑和思路和过程。
1.安装 模板
vue init simulatedgreg/electron-vue img_view
2.先写点简单的。在主进程用fs模块读取指定文件夹下所有图片,返回图片地址数组。在渲染进程页面created时通知主进程,主进程返回图片地址数组。把数组展示在页面中。
3.主进程中引入监听渲染进程的事件,在合适的时间(fs完成)返回图片地址
const path = require('path');
const fs = require('fs');
const {ipcMain} = require('electron')
// const img_path = path.win32.basename('D:\\workfile\\img');
const img_path = "D:\\workfile\\img" //暂时写死
const fs_img_path = new Promise((resolve, reject)=>{ //试试promise
fs.readdir(img_path,(err,files)=>{
if(err){
reject(err)
}else {
resolve(files)
}
})
})
ipcMain.on('created', (event) => { //监听渲染进程的 created 事件
console.log('created')
fs_img_path.then(files=>{
console.log(files)
let fileArr = files.map(v=>{
return path.join(img_path,v) //换成绝对地址
})
event.sender.send('back-imgArr',fileArr) //发送 back-imgArr 事和地址数组
}).catch(err=>{
event.sender.send('back-imgArr',[])
console.log(err)
})
})
3.渲染进程在合适的时间(created)向主进程索取数据,然后监听主进程的事件后得到数据并渲染
export default {
name: 'landing-page',
components: {SystemInformation},
data(){
return{
imgArr:[]
}
},
created() {
this.$electron.ipcRenderer.send('created'); //可以请求数据了
this.$electron.ipcRenderer.on('back-imgArr', (event, arg) => { //成功获得了返回的数据
console.log(arg) // prints "pong"
this.imgArr = arg;
})
},
methods: {
open(link) {
this.$electron.shell.openExternal(link)
},
consoleArr(){ //绑定在了一个按钮上,点击输出
console.log(this.imgArr);
}
}
}
4.总结
第一步没遇到啥大问题(总感觉哪里怪怪的)。接下来先写写页面,然后做个点击图片弹出详情的效果
Since the
main
process is bundled usingwebpack
, the use of__dirname
&__filename
will not provide an expected value in production. Referring to the File Tree, you'll notice that in production themain.js
is placed inside thedist/electron
folder. Based on this knowledge, use__dirname
&__filename
accordingly.If you are in need of a path to your
static/
assets directory, make sure to read up on Using Static Assets to learn about the super handy__static
variable.
因为打包后main.js在 dist/electron目录下,所以__dirname和__filename在开发时不能以当前目录为准。
有机会试试 __static。