石家庄站列车时刻表,一次备案多个网站,化妆品网站建设实施背景,深圳开公司流程及费用使用electron-vue获取文件夹的路径
记录一次开发过程中遇到的bug#xff0c;我们的项目中需要将vue项目打包为桌面应用软件#xff0c;为此我们引入了electron框架#xff0c;在这个过程中#xff0c;我们需要获取到用户电脑上面文件夹的绝对路径#xff0c;用这篇文章记…使用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 electronapp.on(ready, async () {if (isDevelopment !process.env.IS_TEST) {// Install Vue Devtoolstry {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 来触发打开文件对话框的操作
templateButton typeinfo stylewidth: 100% clickhandleSaveChart保存/Button
/templatescriptimport {ipcRenderer} from electronexport 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文件