我正在按照 vue-socket.io
npm download page 上的说明进行操作.但是,我无法使用 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/');
我希望记录传递给 getAllOnline()
函数的任何值。但只有 sockets
对象中的 connect()
回调被触发。
为什么 getAllOnline
的回调没有被触发?
完成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>'
})
最佳答案
您似乎没有正确配置服务器上的代码来处理此自定义事件。
Vue 组件的 created
Hook 中的 this.$socket.emit('getAllOnline', '123213')
调用正在向服务器发出信号'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);
});
});
在上面的示例中,服务器将 getAllOnline
事件与 token
值一起发送回客户端。该值是在该事件的 sockets
回调中处理的值:
sockets: {
getAllOnline(tokenFromServer) {
console.log('getAllOnline', tokenFromServer);
}
},
关于javascript - VueJS : Custom Socket. io 发射在触发时未得到处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44063655/