VueJS的Websocket插件 - vue-websocket

2016-11-11      50      Vue
项目简介

vue-websocket

VueJS的Websocket (socket.io) 插件。支持namespace。

Install

NPM

你可以通过NPM安装 .

$ npm install vue-websocket

Manual

下载这个zip包并解压缩,并将vue-websocket.js文件从dist文件夹中添加到你的项目中。

https://github.com/icebob/vue-websocket/archive/master.zip

Usage

注册插件

import VueWebsocket from "vue-websocket";
Vue.use(VueWebsocket);

or connect to other address:

Vue.use(VueWebsocket, "ws://otherserver:8080");

你也可以传递选项:

Vue.use(VueWebsocket, "ws://otherserver:8080", {
    reconnection: false
});

在你的组件中使用它:

<script>
    export default {

        methods: {
          // Emit the server side
          this.$socket.emit("add", { a: 5 });    
        },

        socket: {
            // prefix: "/counter/",
            // namespace: "/counter",

            events: {

                // Similar as this.$socket.on("changed", (msg) => { ... });
                changed(msg) {
                    console.log("Something changed: " + msg);
                }

                /*
                connect() {
                    console.log("Websocket connected to " + this.$socket.nsp);
                },

                disconnect() {
                    console.log("Websocket disconnected from " + this.$socket.nsp);
                },

                error(err) {
                    console.error("Websocket error!", err);
                }
                */

            }
        }
    };

</script>

Build

这个命令行将会在dist目录中创建一个发布版本。

npm run build

Test

npm test