2016-09-02 8 views
0

これはVue-Socket.ioの簡単な実験です。Vue-Socket.ioでカスタムソケットメソッドを正しく作成する方法は?

Expressは、index.htmlをローカルに提供するために使用されます。

ソケットはhttp://metinseylan.com:1923によって処理されています。

main.jsというカスタムソケットをtestClickedという名前で定義しました。テストボタンは、Vue.jsを介してclickButton()メソッドにバインドされています。 clickButton()の内部2が通話放出されています

this.$socket.emit('connect', val);   // Works 
this.$socket.emit('testClicked', val);  // Fails 

を最初の1が動作する理由を私は理解していないが、もう一つは失敗します。コンソールの出力を一番下に置きます。

また、vue-socketio.jsの中にtestClickedvar methods = [...];を追加しようとしましたが、役に立たなかった。

index.htmlを

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>vue-socket-dynamo</title> 
    </head> 
    <body id="vue-socket-dynamo"> 
     <button @click="clickButton('testing 123')">Test</button> 

     <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script> 
     <script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
     <script src="vue.js"></script> 
     <script src="vue-socketio.js"></script> 
     <script src="main.js"></script> 
    </body> 
</html> 

VUE-socketio.js copy and pasted from here

main.js

var metin = 'http://metinseylan.com:1923'; 

Vue.use(VueSocketio, metin); // Automatically socket connect from url string 

var vm = new Vue({ 
    el: '#vue-socket-dynamo', 
    sockets:{ 
     connect: function(val){ 
      if(val) { console.log('socket connected -> val: ', val); } 
      else { console.log('socket connected'); } 
     }, 
     testClicked: function(val){ 
      console.log('testClicked method fired by socket server. eg: io.emit("customEmit", data)'); 
      if(val) { console.log('val: ', val); } 
     } 
    }, 
    methods: { 
     clickButton: function(val){ 
      // $socket is socket.io-client instance 
      console.log('@click=clickButton Triggered');   // This works. 
      console.log('Input val: ', val); 
      this.$socket.emit('connect', val);   // Works 
      this.$socket.emit('testClicked', val); // NOT WORKING 
     } 
    } 
}); 

vue-socket.io console output

答えて

1

は、サーバー側でEMIT方法をコード化持っていますか?

mySocketIo/index.js 

module.exports = { 
    init: function (server) { 
    var io = require('socket.io') 
    var listeningIo = io.listen(server, null) 
    var listeningIoChat = listeningIo.of('/chat') 
    listeningIoChat.on('connection', function (socket) { 
     console.log('a user connected to chat') 
     socket.on('testClicked', function (msg) { 
     console.log("testClicked") 
     listeningIoChat.emit('testClicked', msg); // this line will trigger the VueSocketio event 
     }); 
     socket.on('disconnect', function() { 
     console.log('user disconnected'); 
     }); 
    }); 
    } 
} 
関連する問題