VueJS:自定义Socket.io发出触发时没有得到处理
我正在按照vue-socket.io
npm下载页面上的说明进行操作。 但是,我不能得到this.$socket.emit
方法来工作。
我有这个在我的Main.vue
组件:
sockets: { connect() { console.log('socket connected') }, getAllOnline(token) { console.log(`Your token is ${token}`) } }, created() { this.$socket.emit('getAllOnline', '123213') }
我在我的main.js
文件中设置了VueSocketio
,如下所示:
import VueSocketio from 'vue-socket.io'; Vue.use(VueSocketio, 'http://localhost:8080/');
我期待logging任何传递给getAllOnline()
函数的值。 但是只有sockets
对象中的connect()
callback被触发。
为什么不触发getAllOnline
的callback?
完整的main.js
文件:
// require some files require('./assets/css/reset.css') require('./assets/css/common.css') // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' import VueRouter from 'vue-router' import VueSocketio from 'vue-socket.io'; // Files import import Main from './components/Main' import Auth from './components/Auth' import Register from './components/Register' // Config of Vue Vue.config.productionTip = false Vue.config.devtools = true // Config of Axios axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' // Register to vue Vue.use(VueRouter) Vue.use(VueAxios, axios) Vue.use(VueSocketio, 'http://localhost:8080/'); // API URL const apiUrl = 'http://localhost/vue-dev/first-app/src/api/' // Router const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', props: { apiUrl: apiUrl }, component: Main }, { path: '/auth', props: { apiUrl: apiUrl }, component: Auth }, { path: '/register', props: { apiUrl: apiUrl }, component: Register } ] }) // Check if the route is exist on the routes router.beforeEach((to, from, next) => { if(to.matched.length === 0) { return router.push('/auth') } return next() }) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<router-view></router-view>' })
看来你没有正确地configuration服务器上的代码来处理这个自定义事件。
this.$socket.emit('getAllOnline', '123213')
在你的Vue组件created
钩子中调用时发出一个信号给服务器'http://localhost:8080/'
。 如果服务器没有监听getAllOnline
事件,则不会发生任何事情。
服务器代码需要监听事件,并将事件发送回客户端。 它看起来像这样:
io.on('connection', function(socket){ socket.on('getAllOnline', function(token){ // code to handle the token goes here io.emit('getAllOnline', token); }); });
在上面的示例中,服务器使用token
值将getAllOnline
事件返回给客户端。 该值是在该事件的sockets
callback中处理的内容:
sockets: { getAllOnline(tokenFromServer) { console.log('getAllOnline', tokenFromServer); } },
试试this.$socket.emit('getAllOnline', '123213')