vue3 electron 记录
Posted npm install bugs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3 electron 记录相关的知识,希望对你有一定的参考价值。
vue3+electron打包成桌面应用
自己记录,vue3+electron打包成.exe桌面应用,部分代码也是c来的,自己修改了一番,也算整合
记录自己开发中的心得
文章目录
前言
废话不多说
一、vuecli打包之后修改公共请求地址
在public文件夹下新建baseUrl.js文件,写如var baseurl = 'http://192.168.x.xx:8080/xx/'同级index.html中
<script src="./baseUrl.js"></script>
<script>
sessionStorage.setItem("baseurl",baseurl);
存入缓存中
二、封装公共axios
依据个人习惯,在src目录下新建utils文件夹,新建http.js
// http.js
import axios from 'axios'
import {
ElLoading,
ElMessage
} from 'element-plus';
//创建axios的一个实例
//统一接口实例方法
var http = axios.create({
baseURL: sessionStorage.getItem('baseurl'), //接口统一域名
timeout: 10000, //设置超时
transformRequest: [//转换为formdata
function (oldData) {
let newStr = '';
for (let item in oldData) {
newStr += encodeURIComponent(item) + '=' + encodeURIComponent(oldData[item]) + '&'
}
newStr = newStr.slice(0, -1);
return newStr
}
],
headers: {
"Content-Type": 'application/x-www-form-urlencoded;charset=UTF-8',
}
})
//通用加载模态框
let loading;
//正在请求的数量
let requestCount = 0
//显示loading
const showLoading = () => {
requestCount++;
loading = ElLoading.service({
text: "请求数据中",
background: 'rgba(0, 0, 0, 0.1)',
spinner: 'el-icon-loading',
})
}
//隐藏loading
const hideLoading = () => {
requestCount--
if (requestCount == 0) {
loading.close()
}
}
//请求拦截器
http.interceptors.request.use((config) => {
showLoading()
// 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
// const token = window.localStorage.getItem('token');
// token && (config.headers.Authorization = token)
return config;
}, (error) =>
// 对请求错误做些什么
Promise.reject(error));
//响应拦截器
http.interceptors.response.use((response) => {
hideLoading()
//响应成功
// console.log('拦截器报错');
return response.data;
}, (error) => {
console.log(error)
//响应错误
if (error.response && error.response.status) {
const status = error.response.status
let message = '';
switch (status) {
case 400:
message = '请求错误';
break;
case 401:
message = '请求错误';
break;
case 404:
message = '请求地址出错';
break;
case 408:
message = '请求超时';
break;
case 500:
message = '服务器内部错误!';
break;
case 501:
message = '服务未实现!';
break;
case 502:
message = '网关错误!';
break;
case 503:
message = '服务不可用!';
break;
case 504:
message = '网关超时!';
break;
case 505:
message = 'HTTP版本不受支持';
break;
default:
message = '请求失败'
}
ElMessage.error(message);
hideLoading()
return Promise.reject(error);
} else {
ElMessage.error('连接服务器失败');
hideLoading()
}
return Promise.reject(error);
});
//导出
export { http }
同级新建request.js
// http/axios.js
import { http } from "./http"
// import httpWeather from "./http"
/**
* @param {String} method 请求的方法:get、post、delete、put
* @param {String} url 请求的url:
* @param {Object} data 请求的参数
* @param {Object} config 请求的配置
* @returns {Promise} 返回一个promise对象,其实就相当于axios请求数据的返回值
*/
const axios = ({
method,
url,
data,
config
}) => {
method = method.toLowerCase();
if (method == 'post') {
return http.post(url, data, { ...config })
} else if (method == 'get') {
return http.get(url, {
params: data,
...config
})
} else if (method == 'delete') {
return http.delete(url, {
params: data,
...config
})
} else if (method == 'put') {
return http.put(url, data, { ...config })
} else {
console.error('未知的method' + method)
return false
}
}
// export default axios
export { axios }
utils文件夹同级新建apis文件夹用来创建每个页面的接口方法,在文件下下新建如details.js
import { axios } from "../utils/request"
//提交修改方法
export const getPagesData = (data) => {
return axios({
url: 'monitorRecord/getMonitorRecordPage',
method: 'post',
data,
})
}
在details.vue页面引用
import { getPagesData } from "../apis/details";
getPagesData({
pageSize: pageSize.value,
currentPage: currentPage.value,
}).then((res) => {
tableData.value = res.page.list;
count.value = res.page.count;
});
至此,封装axios完成
三、组件传值
1.父组件(details.vue)
代码如下(示例):
引入
import v_setting from "../components/setting.vue";
--
申明
components: { v_setting, v_video },
--
使用
<v_setting
@getSetting="getSettingData"
:msg="showTags"
v-show="showTagsNum == true"
:class="[
{ animate__bounceInDown: showTags },
{ animate__bounceOutDown: !showTags },
]"
class="showThem animate__animated"
></v_setting>
--
//获取子组件数据
const getSettingData = (data) => {
这里可以获取子组件传来的数据
setTimeout(() => {
showTagsNum.value = data;
}, 1000);
showTags.value = !showTags.value;
};
2.子组件(setting.vue)
代码如下(示例):
代码不全,仅供参考
export default {
props: {
msg: Boolean,
},
setup(prpos, context) {
--
onMounted(() => {
这里可以获取父组件传来的信息
outSatate.value = prpos.msg;
if (localStorage.getItem("checkState")) {
on.value = localStorage.getItem("checkState");
}
});
--
这里通过context.emit("方法名",参数)调用父组件方法使之获取子组件的值
const closeTag = () => {
outSatate.value = false;
context.emit("getSetting", false);
};
至此,子父组件通讯完成
四、websocket通讯
utils文件夹下新建websocket.js
import {
ElMessage
} from 'element-plus';
let socket = null;
let lockReconnet = false; //避免重复连接
const wsUrl = '';
let isReconnet = false;
let globalCallback = null; //把要发送给socket的数据和处理socket返回数据的回调保存起来
let createSocket = url => { //创建socket
try {
if ('WebSocket' in window) {
socket = new WebSocket(url)
}
initSocket()
} catch (e) {
reconnet(url)
}
}
let sendMsg = (data, callback) => {
if (socket.readyState === 1) {
globalCallback = callback;
data = JSON.stringify(data);
socket.send(data);
} else {
setTimeout(() => {
// console.log(socket, '等待socket链接成功')
sendMsg(data, callback)
}, 5500)
return false
}
socket.onmessage = ev => {
callback && callback(ev)
}
}
let initSocket = () => { //初始化websocket
socket.onopen = () => {
if (socket.readyState === 1) {
ElMessage({
message: 'websocket连接成功',
type: 'success'
})
}
//heartCheck.reset().start() //心跳检测
if (isReconnet) {//执行全局回调函数
//console.log('websocket重新连接了')
sendMsg(globalCallback)
isReconnet = false
}
// socket.send(JSON.stringify({
// "cmd": "SET_AREA",
// "monitorAreaNo": sessionStorage.getItem("area")
// }))
}
// socket.onmessage = () => {
// // sessionStorage.setItem("", host);
// // console.log(ev,'连接正常')
// //heartCheck.reset().start() //心跳检测
// }
socket.onerror = () => {
ElMessage({
message: 'websocket连接出错',
type: 'error'
})
reconnet(wsUrl)
}
socket.onclose = () => {
ElMessage({
message: 'websocket连接关闭',
type: 'error'
})
reconnet(wsUrl)
}
}
let closeSocket = () => { //发送数据,接收数据
socket.close();
}
let getSocketState = () => {
return socket.readyState
}
let reconnet = url => { //重新连接websock函数
if (lockReconnet)
return false
isReconnet = true;
lockReconnet = true
setTimeout(() => {
createSocket(url)
lockReconnet = false
}, 2000)
}
// let heartCheck = { //心跳检测
// timeout: 60*1000,
// timeoutObj: null,
// serverTimeoutObj: null,
// reset(){
// clearTimeout(this.timeoutObj)
// clearTimeout(this.serverTimeoutObj)
// return this;
// },
// start(){
// let that = this;
// this.timeoutObj = setTimeout(()=>{
// //发送数据,如果onmessage能接收到数据,表示连接正常,然后在onmessage里面执行reset方法清除定时器
// socket.send('heart check')
// this.serverTimeoutObj = setTimeout(()=>{
// socket.close()
// },that.timeout)
// },this.timeout)
// }
// }
export { sendMsg, createSocket, closeSocket, getSocketState }
在页面中使用
import { createSocket, getSocketState } from "../utils/websocket";
createSocket(sessionStorage.getItem("websocketurl"));
--
获取当前socket状态
SocketState.value = getSocketState();
--
import { sendMsg } from "../utils/websocket";
发送和接收socket消息
sendMsg(
{
cmd: "SET_AREA",
monitorAreaNo: areaId.value,
},
(ev) => {
//有推送显示提示
if (JSON.parse(ev.data)) {
//判断用户是否在操作或操作等待
if (showVideo.value == true || isChangeState.value == true) {
isHasTips.value = false;
//提示用户有新消息
ElNotification({
title: "提示",
message: "有新的错误提示,请返回表格第一页查看!",
type: "warning",
});
} else {
isHasTips.value = true;
}
tips_ydh.value = JSON.parse(ev.data).waybillNo;
tips_time.value = changeToDateTime(JSON.parse(ev.data).gmtCreate);
//调用分页接口
getPagesData({
pageSize: pageSize.value,
currentPage: currentPage.value,
}).then((res) => {
tableData.value = res.page.list;
count.value = res.page.count;
});
}
}
);
--
import { closeSocket } from "../utils/websocket";
--
客户端主动关闭通讯
closeSocket();
至此,websocket已完成
五、打包.exe
项目安装electeon
npm install electron
项目打包 npm run build
在打包完成后的dist文件夹内新建main.js和package.js文件
main.js
const { app, BrowserWindow } = require('electron');//引入electron
// 获取可执行文件位置
--开机自动启动
const ex = process.execPath;
app.setLoginItemSettings({
openAtLogin: true,
path: ex,
args: []
});
function createWindow() {
win = new BrowserWindow({ show: false })
win.on('ready-to-show', function () {
win.show()
win.maximize()
// 初始化后再显示
})
if (process.env.WEBPACK_DEV_SERVER_URL) {// dev环境
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
} else {// 打包环境
// createProtocol('app')
win.loadURL(`file://${__dirname}/index.html`);
}
// win.loadURL(`file://${__dirname}/index.html`);//在窗口内要展示的内容index.html 就是打包生成的index.html
// win.webContents.openDevTools(); //开启调试工具
win.on('close', () => {
//回收BrowserWindow对象
win = null;
});
去除缩放页面重新加载
// win.on('resize', () => {
// // win.reload();
// })
}
//托盘
app.on('ready', createWindow);
app.on('window-all-closed', () => {
app.quit();
});
app.on('activate', () => {
if (win == null) {
createWindow();
}
});
package.js
{
"name": "yi-feng-video",
"productName": "视频预警",用户看到的名称
"author": "xxx",
以上是关于vue3 electron 记录的主要内容,如果未能解决你的问题,请参考以下文章
前端实战:electron+vue3+ts开发桌面端便签应用
Vue3官网-高级指南(十七)响应式计算`computed`和侦听`watchEffect`(onTrackonTriggeronInvalidate副作用的刷新时机`watch` pre)(代码片段