|
| 1 | +# Web Sockets |
| 2 | + |
| 3 | +This functions provides simple websocket client capabilities. |
| 4 | + |
| 5 | +## State |
| 6 | + |
| 7 | +The `useWebSocket` function exposes the following reactive state: |
| 8 | + |
| 9 | +```js |
| 10 | +import { useWebSocket } from 'vue-use-web'; |
| 11 | + |
| 12 | +const { state, data } = useWebSocket('ws://websocketurl'); |
| 13 | +``` |
| 14 | + |
| 15 | +| State | Type | Description | |
| 16 | +| ----- | ------------- | ------------------------------------------------------------------------------------------------------- | |
| 17 | +| state | `Ref<string>` | The current websocket state, can be only one of: 'OPEN', 'CONNECTING', 'CLOSING', 'CLOSED' | |
| 18 | +| data | `Ref<object>` | Reference to the latest data received via the websocket, can be watched to respond to incoming messages | |
| 19 | + |
| 20 | +## Methods |
| 21 | + |
| 22 | +`useWebSocket` exposes the following methods: |
| 23 | + |
| 24 | +```js |
| 25 | +import { useWebSocket } from 'vue-use-web'; |
| 26 | + |
| 27 | +const { send, close } = useWebSocket('ws://websocketurl'); |
| 28 | +``` |
| 29 | + |
| 30 | +| Method | Signature | Description | |
| 31 | +| ------ | ------------------------------------------ | -------------------------------------------- | |
| 32 | +| send | `(data: any) => void` | Sends data through the websocket connection. | |
| 33 | +| close | `(code?: number, reason?: string) => void` | Closes the websocket connection gracefully. | |
| 34 | + |
| 35 | +## Example |
| 36 | + |
| 37 | +```vue |
| 38 | +<template> |
| 39 | + <div> |
| 40 | + <input type="text" v-model="message" /> |
| 41 | + <button @click="send(message)">Send</button> |
| 42 | + <button @click="close()">Close</button> |
| 43 | + State: {{ state }} |
| 44 | + List of messages: |
| 45 | + <pre>{{ messages }}</pre> |
| 46 | + </div> |
| 47 | +</template> |
| 48 | +
|
| 49 | +<script> |
| 50 | +import { ref, watch } from '@vue/composition-api'; |
| 51 | +import { useWebSocket } from 'vue-use-web'; |
| 52 | +
|
| 53 | +export default { |
| 54 | + setup() { |
| 55 | + const { data, state, send, close } = useWebSocket('ws://demos.kaazing.com/echo'); |
| 56 | + const message = ref(''); |
| 57 | + const messages = ref([]); |
| 58 | + watch( |
| 59 | + data, |
| 60 | + val => { |
| 61 | + messages.value.push(val); |
| 62 | + }, |
| 63 | + { lazy: true } |
| 64 | + ); |
| 65 | +
|
| 66 | + return { state, send, close, data, message, messages }; |
| 67 | + } |
| 68 | +}; |
| 69 | +</script> |
| 70 | +``` |
| 71 | + |
| 72 | +## Demo |
| 73 | + |
| 74 | +TODO: Cool Chat app maybe |
0 commit comments