【发布时间】:2017-10-19 04:57:28
【问题描述】:
我正在按照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>'
})
【问题讨论】:
-
尝试将
sockets: { ...属性定义移动到main.js中的new Vue实例 -
感谢您的帮助,我使用 RxJS 解决了我的问题。
标签: javascript node.js sockets socket.io vuejs2