Vue Socket IO 的使用

安装依赖包

yarn add socket.io
yarn add vue-socket.io

配置

main.js

import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://socket.host',
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    },
    options: {
        autoConnect: false
    //     forceNew: true,
    }
}))

如果 autoConnect 设置为 false 则需要手动连接服务,一般情况如果应用功能是需要登陆后使用的,会设置为 false 以节省连接资源

app.vue

    const project = 'data.project'

    export default {
        name: 'App',
        sockets: {
            connect: function() {
                this.$socket.emit('joinroom', { project, limit: 10 })
                // this.$socket.emit('事件名称与服务端保持一致', 参数1,参数2,...);
            },
            disconnect: function () {
            },
            error: function () {
            },
            demand: function () {
            },
            push: function () {
            }
        },
        mounted() {
            if (this.isLogged) {
                this.$socket.connect()
            }
        },
        computed: {
            isLogged() {
                return this.$store.getters.user.isLogged
            }
        },
        watch: {
            isLogged(val) {
                if (val) {
                    this.$socket.connect()
                }
            }
        },
    }

Socket Store
src/store/global.js

export default {
    state: {
       demand: [],
        // 时实推荐
        realtime: [],
    },
    mutations: {
        SOCKET_demand(state, data) {
            // 接收到数据处理
       },
        SOCKET_push(state, data) {
           // 推送数据请求
        }
    },
    actions: {}
}

你可能感兴趣的:(Vue Socket IO 的使用)