Vue-Socket.io

Posted FAN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue-Socket.io相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

vue-socket.io跨域问题的解决方法

websocket 实现 前端vue-socket.io 服务端 koa2(socket.io)

vue-socket.io 及 egg-socket.io 的简单使用

Vue 使用 Vue-socket.io 实现即时聊天应用(通讯篇)

如何修复套接字 io 中的 400 错误错误请求?

在vue中使用socket.io