vue-socket.io接收不到數(shù)據(jù)問題的解決方法
最近公司的一個vue項目用到了vue-socket.io來處理socket數(shù)據(jù)傳輸,之前用過socket.io-client,現(xiàn)在知道vue-socket.io是基于socket.io-client的一層封裝,將socket掛于全局從而更方便的書寫。
于是把代碼拉取下來運行:
什么鬼,同樣的代碼為什么我的就接收不到數(shù)據(jù),自己新建一個測試一下吧!
先用express和socket.io搭個小socket服務器:
let express = require('express'); let app = express(); let server= require('http').Server(app); let io = require('socket.io')(server); io.on('connect', (socket) => { setInterval(() => { socket.emit('hi','hello') },2000) socket.on('hello', (data) => { console.log('hello',data) socket.emit('hi','get it') }) socket.on('disconnect', (data) => { console.log('斷開', data) }) }) server.listen(8080);
再搭個vue-cli3環(huán)境,main.js里use一下socket:
import Vue from 'vue' import App from './App.vue' import VueSocketIO from 'vue-socket.io' Vue.config.productionTip = false Vue.use(new VueSocketIO({ debug: true, connection: 'http://127.0.0.1:8080', })) new Vue({ render: h => h(App), }).$mount('#app')
再去組件里監(jiān)聽一下:
<script> export default { sockets: { connect() { console.log('鏈接成功'); }, disconnect() { console.log('斷開鏈接') }, reconnect() { console.log('重新鏈接') }, hi(res) { console.log('VueSocketIO', res) } } } </script>
結(jié)果:
為什么,是socket數(shù)據(jù)沒發(fā)送過來嗎?我裝個socket.io-client試試:
import io from 'socket.io-client' export default { mounted() { io('http://127.0.0.1:8080').on('hi', (res) => { console.log('socket.io-client', res) }) }, }
沒問題,數(shù)據(jù)傳過來了,但vue-socket.io為啥不行,不管了,先向服務端發(fā)送一條信息看能不能收到:
this.$socket.emit('hello','i am wk')
沒問題,收到了,所以現(xiàn)在是socket已經(jīng)連接上了,客戶端可以向服務端正常發(fā)送數(shù)據(jù),但服務端也向客戶端發(fā)送數(shù)據(jù)了,上面用socket.io-client可以正常接收已經(jīng)證明這一點了,問題是vue-socket.io沒有正確寫法去接收數(shù)據(jù),似乎api上的寫法出bug了。
打印一下this發(fā)現(xiàn)因為引入vue-socket.io的原因,this上面掛了一個sockets屬性:
this.sockets下有一個listener屬性,看這個名字就感覺有戲,試一下:
this.sockets.listener.subscribe('hi', (data) => { console.log('++++++++++',data) })
哇哦,可以用,好吧,就先這樣用吧,雖然還是不知道sockets:{}這種的寫法為什么不起作用。
到此這篇關(guān)于vue-socket.io接收不到數(shù)據(jù)問題的解決方法的文章就介紹到這了,更多相關(guān)vue-socket.io接收不到數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue elementUi+sortable.js實現(xiàn)嵌套表格拖拽問題
這篇文章主要介紹了vue elementUi+sortable.js實現(xiàn)嵌套表格拖拽問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06Vue監(jiān)聽Enter鍵的方法總結(jié)與區(qū)別
這篇文章主要給大家介紹了關(guān)于Vue監(jiān)聽Enter鍵的方法與區(qū)別的相關(guān)資料,在Vue中我們可以通過監(jiān)聽鍵盤事件來實現(xiàn)回車鍵切換焦點的功能,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-10-10Vue2?Element?description組件列合并詳解
在使用Vue的時候經(jīng)常會涉及到表格的列合并,下面這篇文章主要給大家介紹了給大家Vue2?Element?description組件列合并的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01element-ui 表格sortable排序手動js清除方式
這篇文章主要介紹了element-ui 表格sortable排序手動js清除方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07