首先寫一個(gè)公共方法?socket.js
functiongetSocket(url, params, callback) {
??let socket;
??if(typeof(WebSocket) === 'undefined') {
????console.log('您的瀏覽器不支持WebSocket');
??} else{
????console.log('您的瀏覽器支持WebSocket');
????// 初始化 WebSocket 對(duì)象,指定要連接的服務(wù)器地址與端口建立連接
????socket = newWebSocket(url);
????// 打開事件
????socket.onopen = function() {
??????console.log('Socket 已打開');
??????socket.send(params);
????};
????// 獲得消息事件
????socket.onmessage = function(msg) {
??????// 發(fā)現(xiàn)消息進(jìn)入, 開始處理前端觸發(fā)邏輯
??????callback(msg, socket);
????};
????// 關(guān)閉事件
????socket.onclose = function() {
??????console.log('Socket 已關(guān)閉');
????};
????// 發(fā)生了錯(cuò)誤事件
????socket.onerror = function() {
??????console.log('Socket 發(fā)生了錯(cuò)誤,請(qǐng)刷新頁(yè)面');
??????// 此時(shí)可以嘗試刷新頁(yè)面
????};
??}
}
export {
??getSocket
};
使用
test.vue
<script>
import {getSocket} from '@/utils/socket.js';
export default{
??data() {
????return{
??????wsData: {}, // 保存 websocket 數(shù)據(jù)對(duì)象
??????form: { // 表單
????????name: '',
????????age: ''
??????}
????}
??},
??beforeDestroy() {
????this.wsData.close(); // 關(guān)閉 websocket
??},
??created() {
????this.getSocketData();
??},
??methods: {
????// 獲取數(shù)據(jù)
????getSocketData() {
??????let params = this.form;
??????getSocket(
????????`ws://path`,
????????JSON.stringify(params),
????????(data, ws) => {
??????????console.log(data, ws);
??????????// 保存數(shù)據(jù)對(duì)象, 以便發(fā)送消息
??????????this.wsData = ws;
????????}
??????);
????},
????// 發(fā)送數(shù)據(jù)
????sendSocketData() {
??????let params = this.form;
??????params.name = 'xx';
??????params.age= '18';
??????this.wsData.send(JSON.stringify(params));
????}
??}
}
</script>