前言:我是在vue+ts環境中寫的
// 引入 import SockJS from 'sockjs-client' import Stomp from 'stompjs'
// 進入主頁時執行連接,瀏覽器有打印說明連接成功,接下來待后端發消息就存儲到store,最后渲染即可 let stomp = null const url = 'http://10.14.2.66:18000/ws' const socket = new SockJS(url, null, { timeout: 30000 }) stomp = Stomp.over(socket) const _this = this //連接 stomp.connect({ userId: 1 }, function() { stomp.subscribe('/user/topic/todo', function(res) {
// 存儲store _this.$store.commit('setMsgContent', res.body) }) stomp.subscribe('/user/topic/loginout', function() {}) })
// 在需要渲染組件中監聽是否有發消息,若發了則在組件中顯示出來
computed: { logMsg() { return this.$store.getters.getMsgContent } }, watch: { logMsg(val) {
// 拿到store中存儲的消息 this.logList = this.logList && this.logList.concat(JSON.parse(val)) localStorage.setItem('logList', JSON.stringify(this.logList)) this.logKey += 1 if (JSON.parse(val).ifFinish) { this.showLoading = false } } },
更詳細的demo源碼見:https://gitee.com/zh888/sock-demo