参考STOMP协议文档地址:springboot之websocket,STOMP协议 - 走看看
在vue中写需要先安装依赖anz
yarn add stompjs
yarn add sockjs-client
安装后运行如果报找不到net模块的问题则运行:yarn add net
<template>
<div class="test" style="background-color: burlywood;">
<div>
<h3>订阅形式</h3>
<label>订阅消息:</label><input type="text" disabled="disabled" v-model="websorketvalue">
</div>
<!-- <canvas id="myCanvas" ref="myCanvas"
width="460" height="240" @mousedown="mousedown" @mouseup="mouseup" @mousemove="mousemove">
</canvas> -->
</div>
</template>
<script>
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default {
data(){
return{
websorketvalue:''
}
},
created() {
},
methods:{
websoketfn(){
let _this=this
var stomp = null;
var url = "http://dev.graphchain.top:1001/chain-api/ws"//地址是后端给的
var ws = new SockJS(url);
stomp = Stomp.over(ws);
//连接
stomp.connect({}, function (frame) {
console.log(frame);
//订阅,一般只有订阅的时候在返回
stomp.subscribe("/topic/public", function (res) {
console.log(res);
// console.log( document.querySelector('#subscribeMsg'));
_this.websorketvalue=res.body//这里取自己需要的值就行
});
});
}
},
mounted() {
this.websoketfn()
}
};
</script>
<style scoped>
</style>
效果图