{"id":21524027,"url":"https://github.com/likaia/vue-native-websocket-vue3","last_synced_at":"2025-05-15T14:07:24.972Z","repository":{"id":39515630,"uuid":"308263206","full_name":"likaia/vue-native-websocket-vue3","owner":"likaia","description":"支持vue3的websocket插件","archived":false,"fork":false,"pushed_at":"2024-10-23T08:35:42.000Z","size":937,"stargazers_count":210,"open_issues_count":6,"forks_count":33,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-05-11T14:17:45.443Z","etag":null,"topics":["typescript","vue","vue-websocket","vue3-websocket","websocket"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/likaia.png","metadata":{"files":{"readme":"README-EN.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-29T08:28:42.000Z","updated_at":"2025-04-19T02:08:27.000Z","dependencies_parsed_at":"2024-11-24T02:16:02.348Z","dependency_job_id":null,"html_url":"https://github.com/likaia/vue-native-websocket-vue3","commit_stats":{"total_commits":32,"total_committers":5,"mean_commits":6.4,"dds":0.3125,"last_synced_commit":"25575e9126f0877e42f269a714230dc6a9c2eeb8"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/likaia%2Fvue-native-websocket-vue3","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/likaia%2Fvue-native-websocket-vue3/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/likaia%2Fvue-native-websocket-vue3/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/likaia%2Fvue-native-websocket-vue3/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/likaia","download_url":"https://codeload.github.com/likaia/vue-native-websocket-vue3/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254355335,"owners_count":22057354,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["typescript","vue","vue-websocket","vue3-websocket","websocket"],"created_at":"2024-11-24T01:20:21.178Z","updated_at":"2025-05-15T14:07:19.959Z","avatar_url":"https://github.com/likaia.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# vue-native-websocket-vue3 \u0026middot; [![npm version](https://img.shields.io/badge/npm-v3.1.6-2081C1)](https://www.npmjs.com/package/vue-native-websocket-vue3) [![yarn version](https://img.shields.io/badge/yarn-v3.1.6-F37E42)](https://classic.yarnpkg.com/zh-Hans/package/vue-native-websocket-vue3)\nOnly supports vue3 websocket plugin\n\nChinese documents please move: [README.md](README.md)\n\n\n\nCompatible handling for Pinia（Thanks to [@chuck](https:github.com Front To End) for the compatible code）\n\n## Plug-in installation\n```bash\nyarn add vue-native-websocket-vue3\n\n# or\n\nnpm install vue-native-websocket-vue3 --save\n```\n\n## Plug-in use\nIf Type Script is enabled in your project, import and use the plugin in the `main.ts` file.\n\nImport and use it in `main.js` if it is not enabled.\n\nWhen using the plug-in, the second parameter is required and is your `websocket` server connection address.\n\n```typescript\nimport VueNativeSock from \"vue-native-websocket-vue3\";\n\n// Use the Vue Native Sock plug-in and perform related configuration\napp.use(VueNativeSock,\"\");\n```\n\n\u003e payAttention：The plugin depends on Vuex, your project must install vuex to use this plugin. For the relevant configuration of vuex, please refer to the content in the plug-in configuration item at the back of the document.\n\n\u003e Similarly, the plugin also supports pinia, you can choose one of vuex and pinia. Please refer to the content in the plug-in configuration item at the back of the document for the related usage configuration of pinia.\n\n### Plug-in configuration items\nThe plug-in provides some configuration options, which improves the flexibility of the plug-in and better adapts to the business needs of developers.\n\n#### Enable Vuex integration\nImport the configuration file of `vuex` in `main.ts | main.js`. When using the plug-in, the third parameter is that the user can pass the configuration item. It is an object type, and the `store` attribute is added to the object. Value is imported vuex.\n\n```typescript\nimport store from \"./store\";\n\napp.use(VueNativeSock,\"\",{\n    store: store\n});\n```\n\u003e If you still don't know how to use it, you can refer to my other open source project[chat-system](https://github.com/likaia/chat-system/blob/master/src/main.ts)。 \n\nIf vuex integration is enabled, state and mutations methods need to be defined in its configuration file. The methods defined in mutations are 6 monitors of websocket, and you can do corresponding operations in these monitors.\n```typescript\nimport { createStore } from \"vuex\";\nimport main from \"../main\";\n\nexport default createStore({\n  state: {\n    socket: {\n      // Connection Status\n      isConnected: false,\n      // Message content\n      message: \"\",\n      // Reconnect error\n      reconnectError: false,\n      // Heartbeat message sending time\n      heartBeatInterval: 50000,\n      // Heartbeat timer\n      heartBeatTimer: 0\n    }\n  },\n  mutations: {\n    // Connection open\n    SOCKET_ONOPEN(state, event) {\n      main.config.globalProperties.$socket = event.currentTarget;\n      state.socket.isConnected = true;\n      // When the connection is successful, start sending heartbeat messages regularly to avoid being disconnected by the server\n      state.socket.heartBeatTimer = setInterval(() =\u003e {\n        const message = \"Heartbeat message\";\n        state.socket.isConnected \u0026\u0026\n          main.config.globalProperties.$socket.sendObj({\n            code: 200,\n            msg: message\n          });\n      }, state.socket.heartBeatInterval);\n    },\n    // Connection closed\n    SOCKET_ONCLOSE(state, event) {\n      state.socket.isConnected = false;\n      // Stop the heartbeat message when the connection is closed\n      clearInterval(state.socket.heartBeatTimer);\n      state.socket.heartBeatTimer = 0;\n      console.log(\"The line is disconnected: \" + new Date());\n      console.log(event);\n    },\n    // An error occurred\n    SOCKET_ONERROR(state, event) {\n      console.error(state, event);\n    },\n    // Receive the message sent by the server\n    SOCKET_ONMESSAGE(state, message) {\n      state.socket.message = message;\n    },\n    // Auto reconnect\n    SOCKET_RECONNECT(state, count) {\n      console.info(\"Message system reconnecting...\", state, count);\n    },\n    // Reconnect error\n    SOCKET_RECONNECT_ERROR(state) {\n      state.socket.reconnectError = true;\n    }\n  },\n  modules: {}\n});\n```\n##### Custom method name\nYou can also customize the default listener event name of custom websocket in `mutations`.\n```typescript\n// mutation-types.ts\nconst SOCKET_ONOPEN = '✅ Socket connected!'\nconst SOCKET_ONCLOSE = '❌ Socket disconnected!'\nconst SOCKET_ONERROR = '❌ Socket Error!!!'\nconst SOCKET_ONMESSAGE = 'Websocket message received'\nconst SOCKET_RECONNECT = 'Websocket reconnected'\nconst SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..'\n\nexport {\n  SOCKET_ONOPEN,\n  SOCKET_ONCLOSE,\n  SOCKET_ONERROR,\n  SOCKET_ONMESSAGE,\n  SOCKET_RECONNECT,\n  SOCKET_RECONNECT_ERROR\n}\n\n// store.ts\nimport { createStore } from \"vuex\";\nimport main from \"../main\";\nimport {\n  SOCKET_ONOPEN,\n  SOCKET_ONCLOSE,\n  SOCKET_ONERROR,\n  SOCKET_ONMESSAGE,\n  SOCKET_RECONNECT,\n  SOCKET_RECONNECT_ERROR\n} from \"./mutation-types\"\n\nexport default createStore({\n  state: {\n  socket: {\n      isConnected: false,\n      message: '',\n      reconnectError: false,\n     }\n  },\n  mutations: {\n    [SOCKET_ONOPEN](state, event)  {\n      state.socket.isConnected = true\n    },\n    [SOCKET_ONCLOSE](state, event)  {\n      state.socket.isConnected = false\n    },\n    [SOCKET_ONERROR](state, event)  {\n      console.error(state, event)\n    },\n    // default handler called for all methods\n    [SOCKET_ONMESSAGE](state, message)  {\n      state.socket.message = message\n    },\n    // mutations for reconnect methods\n    [SOCKET_RECONNECT](state, count) {\n      console.info(state, count)\n    },\n    [SOCKET_RECONNECT_ERROR](state) {\n      state.socket.reconnectError = true;\n    }\n  },\n  modules: {}\n});\n\n// main.js\nimport store from './store'\nimport {\n  SOCKET_ONOPEN,\n  SOCKET_ONCLOSE,\n  SOCKET_ONERROR,\n  SOCKET_ONMESSAGE,\n  SOCKET_RECONNECT,\n  SOCKET_RECONNECT_ERROR\n} from './mutation-types'\n\nconst mutations = {\n  SOCKET_ONOPEN,\n  SOCKET_ONCLOSE,\n  SOCKET_ONERROR,\n  SOCKET_ONMESSAGE,\n  SOCKET_RECONNECT,\n  SOCKET_RECONNECT_ERROR\n}\n\napp.use(VueNativeSock,\"\",{\n  store: store,\n  mutations: mutations\n});\n```\n\n\n#### Enable Pinia integration\nImport `pinia`'s configuration file in `main.js|main.ts`.\n```typescript\n// use Socket Store is pinia's socket configuration file\nimport { useSocketStoreWithOut } from './useSocketStore';\n\nconst store = useSocketStoreWithOut();\n\napp.use(VueNativeSock, \"\", {\n    store: store\n});\n```\n\u003e I specially wrote a demo to demonstrate the integration of pinia, if you need a reference, please go to: [pinia-websocket-project](https://github.com/likaia/pinia-websocket-project)\n\nThe code of pinia's socket configuration file is as follows:\n```typescript\nimport { defineStore } from 'pinia';\nimport { store } from '/@/store';\nimport main from '/@/main';\n\ninterface SocketStore {\n  // Connection Status\n  isConnected: boolean;\n  // Message content\n  message: string;\n  // Reconnect error\n  reconnectError: boolean;\n  // Heartbeat message sending time\n  heartBeatInterval: number;\n  // Heartbeat timer\n  heartBeatTimer: number;\n}\n\nexport const useSocketStore = defineStore({\n  id: 'socket',\n  state: (): SocketStore =\u003e ({\n    // Connection Status\n    isConnected: false,\n    // Message content\n    message: '',\n    // Reconnect error\n    reconnectError: false,\n    // Heartbeat message sending time\n    heartBeatInterval: 50000,\n    // Heartbeat timer\n    heartBeatTimer: 0,\n  }),\n  actions: {\n    // Connection open\n    SOCKET_ONOPEN(event) {\n      main.config.globalProperties.$socket = event.currentTarget;\n      this.isConnected = true;\n      // When the connection is successful, start sending heartbeat messages regularly to avoid being disconnected by the server\n      this.heartBeatTimer = window.setInterval(() =\u003e {\n        const message = 'Heartbeat message';\n        this.isConnected \u0026\u0026\n          main.config.globalProperties.$socket.sendObj({\n            code: 200,\n            msg: message,\n          });\n      }, this.heartBeatInterval);\n    },\n    // Connection closed\n    SOCKET_ONCLOSE(event) {\n      this.isConnected = false;\n      // Stop the heartbeat message when the connection is closed\n      window.clearInterval(this.heartBeatTimer);\n      this.heartBeatTimer = 0;\n      console.log('The line is disconnected: ' + new Date());\n      console.log(event);\n    },\n    // An error occurred\n    SOCKET_ONERROR(event) {\n      console.error(event);\n    },\n    // Receive the message sent by the server\n    SOCKET_ONMESSAGE(message) {\n      this.message = message;\n    },\n    // Auto reconnect\n    SOCKET_RECONNECT(count) {\n      console.info('Message system reconnecting...', count);\n    },\n    // Reconnect error\n    SOCKET_RECONNECT_ERROR() {\n      this.reconnectError = true;\n    },\n  },\n});\n\n// Need to be used outside the setup\nexport function useSocketStoreWithOut() {\n  return useSocketStore(store);\n}\n```\n\nIn order to facilitate the use of pinia outside the component, useSocketStoreWithOut is additionally exported here, otherwise pinia will report an error indicating that the pinia instance cannot be found.\n\nThe store configuration code of pinia is as follows:\n```typescript\nimport type { App } from 'vue';\nimport { createPinia } from 'pinia';\n\nconst store = createPinia();\n\nexport function setupStore(app: App\u003cElement\u003e) {\n  app.use(store);\n}\n\nexport { store };\n```\n\n#### Other configuration\n\u003e The following methods are all passable parameters of the plug-in and can be used with `store`\n\n* Set the websocket sub-protocol default, consider it as an empty string.\n```json\n{\n    \"protocol\": \"my-protocol\"\n}\n```\n* Enable JSON messaging. After enabling, data sending and receiving will use json as the data format.\n```json\n{ \n    \"format\": \"json\"\n}\n```\n\n* Enable automatic reconnection `reconnection`, when enabled, you can configure the number of reconnections `reconnection Attempts` and the reconnection interval duration `reconnection Delay`\n```json\n{\n  \"reconnection\": true,\n  \"reconnectionAttempts\": 5, \n  \"reconnectionDelay\": 3000\n}\n```\n\n* Manually manage connections\n```json\n{\n  \"connectManually\": true\n}\n```\nAfter enabling manual connection management, the connection will not be automatically connected when the project starts. You can call the connection method on a specific component of the project to connect. Call the close method when the component is destroyed to close the connection.\n\u003e If you enable manual connection, you must enable vuex, otherwise this setting will not take effect.\n```typescript\n  // Connect to the websocket server, the parameter is the websocket service address\n  this.$connect(\"\");\n  // Close the connection\n  this.$disconnect();\n  \n  // CompositionAPI\n  proxy.$connect(\"\");\n  proxy.$disconnect(\"\");\n```\n* Custom socket event handling\n  When triggering the mutations event in vuex, you can choose to write your own function processing, do what you want to do, pass in the `pass To Store Handler` parameter when using the plug-in, and if you don’t pass it, use the default processing function. The definition of the default function is as follows:\n```typescript\nexport default class {\n  /**\n   * The default event handler\n   * @param eventName\n   * @param event\n   */\n  defaultPassToStore(\n    eventName: string,\n    event: {\n      data: string;\n      mutation: string;\n      namespace: string;\n      action: string;\n    }\n  ): void {\n    // If the beginning of the event name is not SOCKET_ then terminate the function\n    if (!eventName.startsWith(\"SOCKET_\")) {\n      return;\n    }\n    let method = \"commit\";\n    // Turn the letter of the event name to uppercase\n    let target = eventName.toUpperCase();\n    // Message content\n    let msg = event;\n    // data exists and the data is in json format\n    if (this.format === \"json\" \u0026\u0026 event.data) {\n      // Convert data from json string to json object\n      msg = JSON.parse(event.data);\n      // Determine whether msg is synchronous or asynchronous\n      if (msg.mutation) {\n        target = [msg.namespace || \"\", msg.mutation].filter((e: string) =\u003e !!e).join(\"/\");\n      } else if (msg.action) {\n        method = \"dispatch\";\n        target = [msg.namespace || \"\", msg.action].filter((e: string) =\u003e !!e).join(\"/\");\n      }\n    }\n    if (this.mutations) {\n      target = this.mutations[target] || target;\n    }\n    // Trigger methods in storm\n    if (this.store._p) {\n      // pinia\n      target = eventName.toUpperCase();\n      this.store[target](msg);\n    } else {\n      // vuex\n      this.store[method](target, msg);\n    }\n  }\n}\n```\nWhen you want to customize a function, this function receives 3 parameters:\n* event name \n* event \n* Default event handling, which gives you the option to perform some basic preprocessing before handing over the event to the original handler\n\nBelow is an example\n```typescript\napp.use(VueNativeSock, \"\", {\n  passToStoreHandler: function (eventName, event, next) {\n      event.data = event.should_have_been_named_data\n      next(eventName, event)\n  }\n})\n```\n\n### functions exposed by the plugin\n* `send` Send non-json type data (JSON messaging cannot be enabled when using plugins)\n* `sendObj` Send data of type json (JSON messaging must be enabled when using the plugin)\n* `$connect` Connect to the websocket server (manually manage connections option must be enabled when using the plugin)\n* `onmessage` listening when receiving server push messages\n* `$disconnect` disconnectWebsocketConnection\n\n\u003e payAttention: The above methods are supported in the options API and Composition API. For specific usage, please refer to the documentation of the related functions.\n\n### Use in components\nAfter finishing the above configuration, it can be used in the component. The following shows an example of sending data.\n```typescript\nexport default defineComponent({\n  methods: {\n    clickButton: function(val) {\n        // Call the send method to send data as a string\n        this.$socket.send('some data');\n        // If fomat is configured as json, you can call the send Obj method to send data\n        this.$socket.sendObj({ awesome: 'data'} );\n    }\n  }\n})\n```\n\nMessage monitoring means receiving messages pushed by the websocket server. The sample code for message monitoring is shown below.\n```typescript\n// optionsAPI\nthis.$options.sockets.onmessage = (res: { data: string }) =\u003e {\n  console.log(data);\n}\n\n// CompositionAPI\nimport { getCurrentInstance } from \"vue\";\nconst { proxy } = getCurrentInstance() as ComponentInternalInstance;\nproxy.$socket.onmessage = (res: {\n  data: string;\n}) =\u003e {\n  console.log(data);\n}\n```\n\nSend messages, push messages to the server\n```typescript\n// optionsAPI\nthis.$socket.sendObj({msg: 'msgText'});\n\n// compositionAPI\nconst internalInstance = data.currentInstance;\ninternalInstance?.proxy.$socket.sendObj({\n  msg: \"msgText\"\n});\n```\n\u003e The composition API is written because the vue instance cannot be obtained in the setup, so the instance needs to be stored in the global object after the page is mounted, and then the instance is taken out when it is used. For detailed usage, please refer to the writing in my chat-system: [InitData.ts#L91](https://github.com/likaia/chat-system/blob/cacf587061f3a56198ade33a2c5bebeacec004a5/src/module/message-display/main-entrance/InitData.ts#L91) 、[EventMonitoring.ts#L50](https://github.com/likaia/chat-system/blob/db35173c8e54834a117ac8cb5a3753e75d9b1161/src/module/message-display/main-entrance/EventMonitoring.ts#L50) 、[SendMessage.ts#L73](https://github.com/likaia/chat-system/blob/db35173c8e54834a117ac8cb5a3753e75d9b1161/src/module/message-display/components-metords/SendMessage.ts#L73) 、[contact-list.vue#L620](https://github.com/likaia/chat-system/blob/91fe072a20d0928ff2af6c1bf56cedd0e545d0d5/src/views/contact-list.vue#L620)\n\n\nRemove message monitoring\n```typescript\ndelete this.$options.sockets.onmessage\n// compositionAPI  writing\ndelete proxy.$socket.onmessage\n```\n\n## Write at the end\nSo far, all the methods of using the plug-in have been introduced.\n\nIf you want to know more about the plug-in source code, please move to the project's Git Hub repository：[vue-native-websocket-vue3](https://github.com/likaia/vue-native-websocket-vue3)\n\nPlease move to the original plugin for Vue 2 version: [vue-native-websocket](https://github.com/nathantsoi/vue-native-websocket)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flikaia%2Fvue-native-websocket-vue3","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flikaia%2Fvue-native-websocket-vue3","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flikaia%2Fvue-native-websocket-vue3/lists"}