Electron Dialog的使用以及打开目录、文件以及读写配置文件

一、需求

在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);
  },
},
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值