美文网首页
vue项目中建立websocket连接

vue项目中建立websocket连接

作者: 3e2235c61b99 | 来源:发表于2020-08-15 11:25 被阅读0次

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>

相关文章

网友评论

      本文标题:vue项目中建立websocket连接

      本文链接:https://www.haomeiwen.com/subject/nktadktx.html