vue3 + electron翻译工具核心代码

一、前言

以下是自己写的一个demo,主要实现的功能有语言翻译、文本复制及外部文本文件导入。
在这里插入图片描述

二、实现代码

1.渲染进程

// api.js
import axios from "axios"
const baidu = 'http://api.fanyi.baidu.com/api/trans/vip'
function checkLang(param) {
    return new Promise((resolve, reject) => {
        axios.post('https://fanyi.baidu.com/langdetect', param).then((res) => {
            resolve(res)
        })
    })
}
function getTranslate(param) {
    return new Promise((reslove, reject) => {
        axios.post(params(baidu + '/translate', param)).then((res) => {
            reslove(res)
        })
    })
}
function params(url, params) {
    if (params) { // 有参数时拼接
        return params ? url + '?' + Object.keys(params)
            .filter(key => params[key] || params[key] === 0)
            .map(key => `${key}=${params[key]}`)
            .toString().replace(/,/g, '&') :
            url
    } else { // 没参数时获取
        let obj = {};
        url.match(/(\w+)=(\w+)/g).forEach(item => {
            Object.assign(obj, {
                [item.split('=')[0]]: item.split('=')[1]
            })
        })
        return obj
    }
}
export default {
    getTranslate,
    checkLang
}
<!-- indev.vue -->
<div class="head">
  <div class="chose_list">
    <el-select v-model="value_src" class="m-2" placeholder="请选择" size="small">
      <el-option
        v-for="item in options_src"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-icon style="margin: 0 20px;cursor: pointer;" @click="change">
      <Switch />
    </el-icon>
    <el-select v-model="value_res" class="m-2" placeholder="请选择" size="small">
      <el-option
        v-for="item in options_res"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-button style="margin-left: 10px;" size="small" type="warning" @click="getVal">翻译</el-button>
    <el-button style="margin-left: 10px;" size="small" type="primary" @click="copy">复制</el-button>
  </div>
  <div class="btn_group">
    <el-button style="margin-left: 10px;" size="small" type="primary" @click="exportfile">导入文本</el-button>
  </div>
</div>
<div class="content">
  <el-input
    v-model="input_src"
    type="textarea"
    placeholder="请输入要翻译的文本"
    maxlength="200"
    show-word-limit
    resize="none"
    rows="10"
    style="margin-right: 10px;"
    @change="checkLang"
    @keyup.enter.native="getVal"
  />
  <el-input v-model="input_res" type="textarea" resize="none" rows="10" />
</div>
// index.vue
import { Switch } from "@element-plus/icons-vue";
import { ref, reactive } from "vue";
import api from "../../api/index";
import crypto from "crypto";
import { ElMessage } from "element-plus";
import { ipcRenderer } from "electron";
const input_src = ref("");
const input_res = ref("");
const value_src = ref("zh");
const value_res = ref("en");
const options_src = reactive([
  { label: "中文", value: "zh" },
  { label: "英文", value: "en" },
  { label: "日文", value: "jp" },
  { label: "韩文", value: "kor" },
  { label: "泰文", value: "th" }
]);
const options_res = reactive([
  { label: "中文", value: "zh" },
  { label: "英文", value: "en" },
  { label: "日文", value: "jp" },
  { label: "韩文", value: "kor" },
  { label: "泰文", value: "th" }
]);
const config = {
  appid: "", // 在百度翻译控制台获取
  appkey: "" // 在百度翻译控制台获取
};
ipcRenderer.on("result", (e, res) => {
  input_src.value = res;
});
function change() {
  let tmp = value_src.value;
  value_src.value = value_res.value;
  value_res.value = tmp;
}
function getVal() {
  let param = { // 接口调用参数
    q: "",
    from: "",
    to: "",
    appid: "",
    salt: "",
    sign: ""
  };
  if (!input_src.value) return;
  param.q = input_src.value;
  param.from = value_src.value;
  param.to = value_res.value;
  param.appid = config.appid;
  param.salt = new Date().getTime();
  let str = config.appid + input_src.value + param.salt + config.appkey;
  const md5 = crypto.createHash("md5");
  md5.update(str);
  const result = md5.digest("hex");
  param.sign = result;
  api.getTranslate(param).then(res => {
    input_res.value = res.data.trans_result[0].dst;
  });
}
function copy() {
  navigator.clipboard?.writeText &&
    navigator.clipboard.writeText(input_res.value);
  ElMessage({
    message: "复制成功",
    type: "success",
    offset: 35,
    duration: 1000
  });
}
function exportfile() {
  ipcRenderer.send("open");
}
function checkLang() {
  let param = {
    query: ""
  };
  if (!input_src.value) return;
  param.query = input_src.value;
  api.checkLang(param).then(res => {
    console.log(res.data.lan);
    value_src.value = res.data.lan;
    if (value_src.value === value_res.value) {
      for (let i = 0; i < options_res.length; i++) {
        if (options_res[i].value === value_res.value) {
          if (options_res[i].value === "zh") {
            value_res.value = options_res[i + 1].value;
          } else {
            value_res.value = options_res[0].value;
          }
          break;
        }
      }
    }
  });
}
/* index.vue */
.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}
.chose_list {
  display: flex;
  align-items: center;
}
.content {
  display: flex;
}
.m-2 {
  width: 100px;
}

2.主进程

import {
  ipcMain,
  BrowserWindow,
  dialog
} from 'electron'
import fs from 'fs'
const win = new BrowserWindow({
  width: 250,
  height: 350,
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    webSecurity: false
  }
})
ipcMain.on('open', () => {
  dialog.showOpenDialog().then((res) => {
    fs.readFile(res.filePaths[0], {
      encoding: "utf-8"
    }, (err, data) => {
      if (err) {
        console.log(err, "读取文件内容失败");
      } else {
        let str = `${data}`.trim().slice(0, 200)
        win && win.webContents.send("result", str) // 往实例化的窗口发送文本信息
      }
    })
  })
})
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值