vue项目中需要给用户推送消息,网上查找资料后,实现代码如下:
<script>
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default {
data() {
return {
stompClient: null
}
},
created() {
this.connect()
},
methods: {
connect() {
const that = this
const IP = process.env.VUE_APP_BASE_API //获取服务器ip
const socket = new SockJS(IP + '/socket') //建立连接,IP + '/socket' 为需要连接的地址
that.stompClient = Stomp.over(socket)
that.stompClient.connect({},
function(frame) {
//通过stompClient.subscribe订阅/topic/apply/userName 目标(destination)发送的消息,下面代码为动态获取用户的ueserName
that.stompClient.subscribe(`/topic/apply/${that.$store.getters.name}`, function(result) {
//收到消息之后处理
that.$message({
message: JSON.parse(result.body).title,
duration: 5000
})
})
})
}
}
}
</script>
网友评论