1.0.2 • Published 3 years ago
vue-rws v1.0.2
🚀 Installation
npm install vue-rws
# or
yarn add vue-rws
Using Connection String
import Vue from "vue";
import store from "./store";
import App from "./App.vue";
import VueRws from "vue-rws";
Vue.use(
new VueRws({
debug: true,
connection: "ws://socket link",
vuex: {
store,
actionPrefix: "SOCKET_",
mutationPrefix: "SOCKET_",
},
//Optional options
options: {
// WebSocket: WS, // custom WebSocket constructor
connectionTimeout: 1000,
maxRetries: 10,
},
})
);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
Using socket.io-client Instance
import Vue from "vue";
import store from "./store";
import App from "./App.vue";
import VueRws from "vue-rws";
import ReconnectingWebSocket from "reconnecting-websocket";
const options = {
// WebSocket: WS, // custom WebSocket constructor
connectionTimeout: 1000,
maxRetries: 10,
}; //Options object to pass into ReconnectingWebSocket
Vue.use(
new VueRws({
debug: true,
connection: new ReconnectingWebSocket("ws://socket link", options), //options object is Optional
vuex: {
store,
actionPrefix: "SOCKET_",
mutationPrefix: "SOCKET_",
},
})
);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
Parameters | Type's | Default | Required | Description |
---|---|---|---|---|
debug | Boolean | false | Optional | Enable logging for debug |
connection | String/reconnecting-websocket | null | Required | Websocket server url or reconnecting-websocket instance |
vuex.store | Vuex | null | Optional | Vuex store instance |
vuex.actionPrefix | String | null | Optional | Prefix for emitting server side vuex actions |
vuex.mutationPrefix | String | null | Optional | Prefix for emitting server side vuex mutations |
options | Object | null | Optional | reconnecting-websocket options |
🌈 Component Level Usage
new Vue({
sockets: {
connect() {
console.log("socket connected");
},
customEmit(data) {
console.log(
'this method was fired by the socket server. eg: rws.emit("customEmit", data)'
);
},
},
methods: {
clickButton(data) {
// $socket is socket.io-client instance
this.$rws.emit("emit_method", data);
},
},
});
Dynamic Listeners
this.sockets.subscribe("EVENT_NAME", (data) => {
this.msg = data.message;
});
this.sockets.unsubscribe("EVENT_NAME");
Defining handlers for events with special characters
export default {
name: "Test",
sockets: {
connect() {
console.log("socket to notification channel connected");
},
},
data() {
return {
something: [
// ... something here for the data if you need.
],
};
},
mounted() {
this.$rws.subscribe("kebab-case", (data) => {
console.log("This event was fired by eg. rws.emit('kebab-case')", data);
});
},
};
🏆 Vuex Integration
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
},
},
});