iT邦幫忙

0

vue,vuex,vue-socket.io,socket.io相關應用問題

最近想實作聊天室的專案
使用了vue,vuex,vue-socket.io,socket.io來實作
不過vue-socket.io在vuex的操作不像在vue裡那麼直觀
看了官方範例後也沒有成功
請想大家幫幫忙,謝謝
官網:vue-socket.io
按照官網我在main.js引入

import Vue from 'vue'
import App from './components/base/App.vue'
import router from './router'
import Vuex from 'vuex'
import VueSocketio from 'vue-socket.io'
import VueSocketioClient from 'socket.io-client'
import store from './store'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.config.productionTip = false
Vue.use(Vuex)
Vue.use(VueSocketio, socketio('http://localhost:3000'), store);
Vue.use(BootstrapVue);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  store
})

結果會在cosole.log出現錯誤

main.js?1c90:16 Uncaught ReferenceError: socketio is not defined
    at eval (main.js?1c90:16)
    at Object../src/main.js (app.js:3497)
    at __webpack_require__ (app.js:679)
    at fn (app.js:89)
    at Object.0 (app.js:3554)
    at __webpack_require__ (app.js:679)
    at app.js:725
    at app.js:728

Vue.use(VueSocketio, socketio('http://localhost:3000'), store);
如果這一串改成
Vue.use(VueSocketio, 'http://localhost:3000', store);
似乎會無法觸發連動
因為伺服器端emit回來的
store方面無法接到

伺服器端

io.on('connection', socket => {
  socketId.push(socket.id);
  console.log(socketId);
  socket.on('addName', name => {
    if(name) {
      names.push(name);
    }
    io.emit('addName', names) ;
  });
  socket.on('whisper', indexData => {
    index = indexData;
  });
  socket.on('message', data => {
    if(!index) {
      io.emit('message', data);
    } else {
      socket.broadcast.to(socketId[index]).emit('message', data);
      console.log(socketId[index]);
    }
  });
});

action

createName({commit}) {
        console.log(username);
        const username = (() => prompt('Name: ', ''))();
        this._vm.$socket.emit('addName', username);
        commit(types.CREATE_NAME, username);
    },

    socket_addName({commit}, names) {
        console.log('name', names)
        commit(types.CREATE_NAMES, names);
    },

    whisper({commit}, index) {
        this._vm.$socket.emit('whisper', index);
        console.log('index', index);
    },

    sendMessage({commit}, data) {
        this._vm.$socket.emit('message', data);
    },

    socket_message({commit}, retData) {
        console.log(retData);
        commit(types.SEND_MESSAGE, retData);
    }

像是socket_addName及socket_message都沒有接收到資料
想請問缺少了哪個要素
謝謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
eric21364
iT邦見習生 ‧ 2018-05-21 22:12:56

import VueSocketioClient from 'socket.io-client'
改成
import socketio from 'socket.io-client'

我要發表回答

立即登入回答