Vue-Socket.io
阿新 • • 發佈:2017-11-11
true his ron fault tom ive ati message 應用
github地址:https://github.com/MetinSeylan/Vue-Socket.io
安裝:
npm install vue-socket.io -S
註冊:
import Vue from ‘vue‘ import VueSocketio from ‘vue-socket.io‘ Vue.use(VueSocketio, ‘http://socketserver.com:1923‘)
實例應用:
var vm = new Vue({ sockets:{ //將(socket.on)綁定事件放在sockets中 connect: function(){ console.log(‘socket connected‘) }, customEmit: function(val){ console.log(‘this method was fired by the socket server. eg: io.emit("customEmit", data)‘) } }, methods: { clickButton: function(val){ // $socket is socket.io-client instance this.$socket.emit(‘emit_method‘, val); } } })
創建一個新的監聽器:
this.$options.sockets.event_name = (data) => {
console.log(data)
}
刪除監聽器:
delete this.$options.sockets.event_name;
觸發服務端事件:
this.$socket.emit(‘event_name‘, msg1,msg2,...);
配合VUEX使用:
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex); export default new Vuex.Store({ state: { connect:false, message: null }, mutations:{ SOCKET_CONNECT: (state, status ) => { state.connect = true; }, SOCKET_USER_MESSAGE: (state, message) => { state.message = message; } }, actions: { otherAction: (context, type) => { return true; }, socket_userMessage: (context, message) => { context.dispatch(‘newMessage‘, message); context.commit(‘NEW_MESSAGE_RECEIVED‘, message); if (message.is_important) { context.dispatch(‘alertImportantMessage‘, message); } ... } } })
Vue-Socket.io