vue-websocket-handler
v0.0.5
Published
a vue websocket handler library
Downloads
6
Readme
vueWebsocketHandler
Description
vueWebsocketHandler is a library used to handle WebSocket by hooks and plugin in Vue3.
usage
install this package
npm install vue-websocket-handler --save
You can use it in a single vue component. In a config file, you can initialize this handler and export it.
import type { WebSocketConfig } from "vue-websocket-handler";
import { useWebSocket } from "vue-websocket-handler";
const webSocketConfig: WebSocketConfig = {
host: "localhost",
port: "8899",
url: "/ws",
emitters: [
() => {
console.log("send msg");
},
],
};
const webSocketHandler = useWebSocket(webSocketConfig);
export { webSocketHandler };
In a *.vue file, you can import this handler and override sendMessage
in setup()
function like this:
import { webSocketHandler } from "../config/webSocket";
import { onMounted } from "vue";
onMounted(() => {
setTimeout(() => {
webSocketHandler.sendMessage!("hello")
}, 3000);
webSocketHandler.onmessage = (event?: MessageEvent) => {
console.log(event);
console.log(event?.data)
};
});
You can also use it by a vue plugin after vue.use()
like
import type { WebSocketConfig } from "vue-websocket-handler";
const webSocketConfig: WebSocketConfig = {
host: "localhost",
port: "8899",
url: "/ws",
emitters: [
() => {
console.log("send msg");
},
],
};
export { webSocketConfig };
And in main.ts , import config and use it
import { useWebSocketPlugin } from "vue-websocket-handler";
import { webSocketConfig } from "./config/webSocket";
const app = createApp(App);
app.use(useWebSocketPlugin, webSocketConfig);
app.mount("#app");
In *.vue file , import WsKey
to inject WebSocketHandler and use it.
import { inject, onMounted } from "vue";
import { WsKey } from "vue-websocket-handler";
onMounted(() => {
let wsh = inject(WsKey);
console.log(wsh);
});
Also, you can use hook function names useInjectWebSocket()
to get a provided WebSocketHandler in setup()
like
import { onMounted } from "vue";
import { useInjectWebSocket } from "vue-websocket-handler";
import { WebSocketHandlerType } from "vue-websocket-handler";
onMounted(() => {
let wsh: WebSocketHandlerType = useInjectWebSocket();
wsh.logVersion();
});
backend sample
websocket server sample in fastapi written in Python. You can write back-end in any other coding language.
from fastapi import FastAPI
from fastapi.websockets import WebSocket
app = FastAPI()
@app.websocket_route("/ws")
async def websocket(websocket: WebSocket) -> None:
await websocket.accept()
r = 'hello'
while True:
msg = r
data = await websocket.receive_text()
print(data)
await websocket.send_json({"msg": msg, "data": data})
if __name__ == '__main__':
import uvicorn
uvicorn.run(
app='main:app',
host="127.0.0.1",
port=8899,
)