vue中开发webSocket

先安装 sockjs-client 和 stompjs

npm install sockjs-client
npm install stompjs

<template>
<div>
<el-row :gutter="5">

<div class="head">WebSocket接收后端数据</div>

<div class="block">
{{content.age}}
</div>
<el-button type="primary">提交</el-button>


</el-row>

</div>
</template>

<script>
import FloorDashboard from './FloorAndArea'
import Stomp from "stompjs"
import SockJS from "sockjs-client"

export default {
name: "Index",
data() {
return {
content: ""
}
},
mounted() {
this.connect();
},
methods: {
connect() {
//连接SockJS的endpoint名称为"endpointOyzc"
let socket = new SockJS('http://test.jd.com:8082/endpointOyzc');
//使用STMOP子协议的WebSocket客户端
let stompClient = Stomp.over(socket);

//连接WebSocket服务端
stompClient.connect({}, () => {
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
// stompClient.subscribe('/topic/getResponse', function (response) { //广播监听数据
stompClient.subscribe('/user/1/message', (response) => {
let dataType = typeof response.body;
switch (dataType) {
case "string":
this.content = JSON.parse(response.body);
console.log("type is string");
console.log(this.content);
break;
case "object":
console.log(this.content);
console.log("type is string");
this.content = response.body;
}
});
});
}
}
}
</script>

<style scoped>

</style>


posted @ 2019-03-29 17:02  雷神约  阅读(839)  评论(0编辑  收藏  举报