一、需求
在Electron中我期望打开某个目录,修改其目录下的某个配置文件要打开目录、或者文件,就需要用到Electron的dialog。
二、启用remote
2.1. 安装@electron/remote
- 安装
@electron/remote
npm install --save @electron/remote
2.2. background.js主进程中启用remote
- 引入remote模块
const remote = require("@electron/remote/main");
- 启用remote模块,渲染进程就可以使用主程序模块
app.on("ready", async () => {
createWindow();
// ********启用remote模块,渲染进程就可以使用主程序模块********************
// win就是createWindow方法创建的实例对象
remote.enable(win.webContents);
});
2.3. 使用dialog
完成以上两个步骤后,我就可以在其他窗口使用dialog了。
- html
<el-form :model="form" label-width="120px">
<el-form-item label="请选择你的文件:">
<el-input
v-model="filePath"
placeholder="请选择你的文件"
readonly
@click="selectDirectory"
/>
</el-form-item>
</el-form>
<el-row>
<el-button @click="readFile">读取配置文件</el-button>
<el-button @click="writeFile">写入配置文件</el-button>
</el-row>
- 引入依赖
const { dialog } = require('@electron/remote')
console.log(dialog, 'dialog')
//引入node原生fs模块
const fs = require("fs")
//引入node原生读写配置
const ini = require('ini');
- data
data() {
return {
filePath: "",
config: null,
};
},
- methods
methods: {
selectDirectory() {
dialog
.showOpenDialog({
properties: ["openFile"], // 选择文件
// properties: ["openDirectory"] // 选择目录
})
.then((results) => {
// console.log(results.filePaths);
// console.log(results.canceled);
this.filePath = results.filePaths[0];
});
},
// 读取配置文件
readFile() {
if (!this.filePath) {
this.errMsg("请先选择文件");
return;
}
this.config = ini.parse(fs.readFileSync(this.filePath).toString());
console.log(this.config, "config");
},
// 写配置文件
writeFile() {
if (!this.config) {
this.errMsg("请先读取文件");
return;
}
this.config.xxxxx = "你想要修改的值";
fs.writeFileSync(this.filePath, ini.stringify(this.config));
},
errMsg(msg) {
dialog.showErrorBox("错误信息", msg);
},
},