参考地址:https://www.npmjs.com/package/vue-socket.io
安装依赖:
npm install vue-socket.io --save
npm install socket.io-client --save
在main.js中引入:
import Vue from 'vue'
import VueSocketio from 'vue-socket.io'
import socketio from 'socket.io-client'
下面这个是重点
Vue.use(new VueSocketIO({
debug: true,
connection: socketio('http://10.10.2.18:3000'),
vuex: {
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_'
},
options: { path: '/my-app/' }
}));实例应用:
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)')
}
},
mounted() {
//这个是连接服务器,event_name服务器给的方法
this.$socket.emit('event_name', loginid);
}
})创建一个新的监听器: (服务器返回的结果,event_name服务器给的方法)
this.sockets.subscribe('event_name', (data) => { this.msg = data.message; });
删除监听器:
this.sockets.unsubscribe('event_name');
触发服务端事件:
this.$socket.emit('event_name', msg1,msg2,...);
在store.js中引入:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {
"<MUTATION_PREFIX><EVENT_NAME>"() {
// do something
}
},
actions: {
"<ACTION_PREFIX><EVENT_NAME>"() {
// do something
}
}
})