使用electron-vue获取文件夹的路径
- 记录一次开发过程中遇到的bug,我们的项目中需要将vue项目打包为桌面应用软件,为此我们引入了electron框架,在这个过程中,我们需要获取到用户电脑上面文件夹的绝对路径,用这篇文章记录一下
修改方式
- 修改vue.config.js
- 在 vue.config.js 中开启了 Electron 集成,这允许你在 Electron 进程中使用 Node.js 功能。
pluginOptions: {
electronBuilder: {
nodeIntegration: true,
contextIsolation: false,
}
}
- 在background.js添加以下内容
- 导入依赖
import {ipcMain,ipcRenderer,dialog} from "electron"
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
createWindow()
// 新增:在主进程中处理打开文件对话框的请求
ipcMain.handle("dialog:openFile",handleFileOpen)
})
// 新增:处理打开文件对话框的函数
async function handleFileOpen(){
const options = {
title: 'Select a Folder',
properties: ['openDirectory']
};
const {canceled,filePaths}=await dialog.showOpenDialog(options)
if (canceled){
console.log(1)
return
}else {
console.log(2,filePaths)
return filePaths[0]
}
}
- 在vue页面中编写触发事件
- 在 Vue 组件中,你使用 ipcRenderer 来触发打开文件对话框的操作:
<template>
<Button type="info" style="width: 100%" @click="handleSaveChart">保存</Button>
</template>
<script>
import {ipcRenderer} from 'electron'
export default {
name: "DirPage",
created() {
// const ipc = require('electron').ipcRenderer;
ipcRenderer.on('save-finished', function (event, filename) {
// 当filename等于null的时候表示用户点击了取消按钮
// 当用户点击保存按钮的时候filename的值是对应文件的绝对路径
console.log(filename)
})
},
methods: {
//获取的文件名称
handleSaveChart: function () {
// 向IPC通道发送信号,此时主线程收到信号立即执行相对应的响应函数
// const ipcRenderer = require('electron').ipcRenderer;
const result = ipcRenderer.invoke('dialog:openFile');
// if (!result.canceled && result.filePaths.length > 0) {
result.then(res=>{
console.log("file",res)
})
// 在这里可以使用 selectedFolder 的绝对路径进行后续操作
// }
}
}
}
</script>
- 总结
-
background.js 中的 ipcMain.handle:这个函数允许你在主进程中注册一个处理函数,当从渲染进程发送请求到主进程时,会调用这个处理函数并返回结果。在这里,我们注册了一个处理函数 handleFileOpen,用于打开文件对话框并返回选中的文件夹路径。
-
Vue 组件中的 ipcRenderer.invoke:这个函数用于从渲染进程向主进程发送请求,并等待主进程的响应。在这里,你向主进程发送了打开文件对话框的请求,并使用 invoke 来等待主进程返回选中的文件夹路径。
-
主线程就是:background.js文件
-
渲染线程就是.vue文件
-