VueJS: Custom Socket.io emits are not getting handled when triggered

Viewed 7928

I'm following the instructions on the vue-socket.io npm download page. However, I can't get the this.$socket.emit method to work.

I have this in my Main.vue component:

sockets: {
    connect() {
        console.log('socket connected')
    },
    getAllOnline(token) {
        console.log(`Your token is ${token}`)
    }
},
created() {
    this.$socket.emit('getAllOnline', '123213')
}

I set up VueSocketio in my main.js file like this:

import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, 'http://localhost:8080/');

I'm expecting to log whatever value was passed to the getAllOnline() function. But only the connect() callback in sockets object is being triggered.

Why isn't the callback for the getAllOnline emit being triggered?


Complete main.js file:

// 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>'
})

2 Answers
Related