前端
<template>
<div class="wrap">
<button @click="socketEmit">连接Socket</button>
<button @click="socketSendmsg">发送数据</button>
</div>
</template>
<script>
export default {
data(){
return {
randomId:null,
}
},
methods:{
socketEmit(){
this.$socket.open();
this.sockets.subscribe('testCall', (res) => {
if(res.code == 200 && res.randomId === this.randomId){
console.log('召唤成功')
}
})
},
socketSendmsg(){
this.randomId = Math.random();
this.$socket.emit('testCall', {
"randomId": this.randomId,
"deviceId": "123456"
});
},
},
sockets: {
connect: function () {
console.log('连接成功')
},
disconnect: function () {
console.log('断开连接')
},
reconnect: function () {
console.log('重新连接')
},
},
beforeDestroy(){
this.sockets.unsubscribe('testCall');
this.$socket.close();
},
}
</script>
main.js
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
debug: true,
connection:'http://metinseylan.com:1992',
options:{
autoConnect: false,
path: "/my-app/",
transports: ['polling'],
extraHeaders:{},
},
}))