在vue项目中使用WebSocket做客服功能

最近在做一个电商平台,里面涉及到了客服,我是用WebSocket做的,emmm。。。有什么不是很好的地方还请各位童鞋们多多担待

data(){

            return{

                    path:"ws://125.57.39.105:8383",(这个是个例子)

                    socket:""

            }

},

mounted() {

            this.init()

},

methods:{

            init: function () {

                    if(typeof(WebSocket) === "undefined"){

                                alert("您的浏览器不支持socket")

                    }else{

                                // 实例化socket

                                this.socket = new WebSocket(this.path)

                                // 监听socket连接

                                this.socket.onopen = this.open

                                // 监听socket错误信息

                                this.socket.onerror = this.error

                                 // 监听socket消息

                                 this.socket.onmessage = this.getMessage

                    }

            },

            open: function () {

                                console.log("socket连接成功")

            },

            error: function () {

                                console.log("连接错误")

            },

            getMessage: function (msg) {

                                 var data = eval("("+msg.data+")");

                                console.log(data)

            },

            send: function () {

                                this.socket.send(params)

            },

            close: function () {

                                console.log("socket已经关闭")

            }

},

destroyed () {

                // 销毁监听

                this.socket.onclose = this.close

}

这样就绑定成功了,然后把后台给你的发送消息的接口放到send里面,历史记录呢要放到getMessage里面。

最后就是把你获取到的信息显示到页面就好了(*^▽^*)(^_−)☆

你可能感兴趣的:(在vue项目中使用WebSocket做客服功能)