一、Axios
1、Axios封装(request.js)
javascript
复制代码
import axios from "axios";
// 开发环境配置
const baseURL = "/api";
// 生产环境配置
// const baseURL = 'http://192.168.0.1:9000'
// 创建axios实例
const http = axios.create({
baseURL: baseURL,
timeout: 5000, // 超时时间
});
// 设置默认请求数据格式
http.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
// 请求拦截
http.interceptors.request.use(
(request) => {
return request;
},
(error) => {
return error;
}
);
// 响应拦截
http.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
return error;
}
);
export default http;
2、示例(api.js)
javascript
复制代码
import http from './request'
// get请求(params = {})
function getRequest(params) {
return http.get(`/api?user=${params.user}&passwd=${params.passwd}`)
}
// post请求(params = {})
function postRequest(params) {
return http.post('/api', params)
}
// put请求(params = {})
function putRequest(params) {
return http.put('/api', params)
}
// delete请求(params = {})
function deleteRequest(params) {
return http.delete('/api', {
data:params
})
}
export default {
getRequest,
postRequest,
putRequest,
deleteRequest
}
二、WebSocket
1、Ws封装(WebSocket.js)
javascript
复制代码
let ws = null;
let _data = null;
let _url = null;
let _callback = null;
let hearBeatTimer = null;
let reconnectTimer = null;
let reconnectNum = 0; // 重连次数
const time = 3000; // 心跳间隔
const reconnectTime = 5000; // 重连超时
// 初始化
export function webSocket(url = "", data = "", callback = () => { }) {
_url = url; // 地址
_data = data; // 发送消息
_callback = callback; // 回调函数,利用闭包
createWebSocket(); // 创建 webSocket
}
// 获取连接
export function getWebSocket() {
return ws;
}
// 创建连接
function createWebSocket() {
if (!_url) return;
if (ws) {
ws.close();
ws = null;
}
ws = new WebSocket(_url);
ws.onopen = function () {
sendMessage();
heartBeat();
};
ws.onmessage = function (e) {
if (typeof _callback === "function") {
_callback(e);
}
reconnectNum = 0;
heartBeat();
};
ws.onerror = function () {
// console.log('链接失败,正在重连');
reconnect();
};
ws.onclose = function () {
reconnect();
};
}
// 关闭连接
export function closeWebSocket() {
if (ws) {
ws.onerror = () => { };
ws.onclose = () => { };
ws.close();
}
ws = null;
_data = null;
_url = null;
_callback = () => { };
hearBeatTimer = null;
reconnectTimer = null;
}
// 心跳检测
function heartBeat() {
if (hearBeatTimer) {
clearTimeout(hearBeatTimer);
}
hearBeatTimer = setTimeout(() => {
// console.log("ws连接状态:", ws.readyState);
if (ws && ws.readyState < 2) {
// 如果连接正常
sendMessage();
} else {
reconnect();
}
}, time);
}
// 发送消息
function sendMessage() {
if (!ws) return;
switch (Object.prototype.toString.call(_data)) {
case "[object Object]":
ws.send(JSON.stringify(_data));
break;
case "[object String]":
ws.send(_data);
}
}
// 重连尝试
function reconnect() {
if (reconnectTimer) {
clearTimeout(reconnectTimer);
}
reconnectTimer = setTimeout(() => {
reconnectNum++;
webSocket(_url, _data, _callback);
}, reconnectTime);
}
2、示例(Home.vue)
javascript
复制代码
<template>
<div class="home">
</div>
</template>
<script>
// webSocket
import { webSocket } from "@/utils/WebSocket";
export default {
name: "",
components: {},
props: {},
data() {
return {};
},
computed: {},
created() {},
mounted() {
this.initWs();
},
methods: {
initWs() {
webSocket("ws://192.168.0.1:9999/new", "", this.wsCallBack)
},
wsCallBack(data){
console.log("webSocket数据", data)
}
},
};
</script>
<style lang="less" scoped>
.home {
width: 100%;
height: 100vh;
}
</style>