Gathering detailed insights and metrics for vue-native-websocket-vue3
Gathering detailed insights and metrics for vue-native-websocket-vue3
npm install vue-native-websocket-vue3
Typescript
Module System
Node Version
NPM Version
TypeScript (90.94%)
JavaScript (9.06%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
234,388
Last Day
821
Last Week
3,981
Last Month
16,422
Last Year
132,161
209 Stars
37 Commits
33 Forks
5 Watchers
1 Branches
4 Contributors
Updated on Mar 07, 2025
Minified
Minified + Gzipped
Latest Version
3.1.8
Package Id
vue-native-websocket-vue3@3.1.8
Unpacked Size
293.66 kB
Size
75.87 kB
File Count
11
NPM Version
6.14.11
Node Version
14.16.0
Published on
Oct 23, 2024
Cumulative downloads
Total Downloads
Last Day
7.7%
821
Compared to previous day
Last Week
-1%
3,981
Compared to previous week
Last Month
27.7%
16,422
Compared to previous month
Last Year
132.6%
132,161
Compared to previous year
1
21
仅支持vue3的websocket插件 | Only supports vue3 websocket plugin
English documents please move: README-EN.md
对Pinia进行兼容处理(感谢@chuck所提供的兼容代码)
1yarn add vue-native-websocket-vue3 2 3# or 4 5npm install vue-native-websocket-vue3 --save
如果你的项目启用了TypeScript,则在main.ts
文件中导入并使用插件。
没有启用就在main.js
中导入并使用。
使用插件时,第二个参数为必填项,是你的websocket
服务端连接地址。
1import VueNativeSock from "vue-native-websocket-vue3"; 2 3// 使用VueNativeSock插件,并进行相关配置 4app.use(VueNativeSock,"");
注意:插件依赖于Vuex,你的项目一定要安装vuex才可以使用本插件。vuex的相关配置请查阅文档后面的插件配置项中的内容。
同样的,插件也支持pinia,vuex与pinia任选其一即可。pinia的相关使用配置请请查阅文档后面的插件配置项中的内容。
插件提供了一些配置选项,提高了插件的灵活度,能更好的适配开发者的业务需求。
在main.ts | main.js
中导入vuex
的配置文件,在使用插件时,第三个参数就是用户可以传配置项,他为一个对象类型,在对象中加入store
属性,值为导入的vuex。
1import store from "./store"; 2 3app.use(VueNativeSock,"",{ 4 store: store 5});
如果你仍然不知道怎么用,可以去参考我的另一个开源项目chat-system。
如果启用了vuex集成,就需要在其配置文件中定义state以及mutations方法。mutations中定义的方法为websocket的6个监听,你可以在这几个监听中做相应的操作。
1import { createStore } from "vuex"; 2import main from "../main"; 3 4export default createStore({ 5 state: { 6 socket: { 7 // 连接状态 8 isConnected: false, 9 // 消息内容 10 message: "", 11 // 重新连接错误 12 reconnectError: false, 13 // 心跳消息发送时间 14 heartBeatInterval: 50000, 15 // 心跳定时器 16 heartBeatTimer: 0 17 } 18 }, 19 mutations: { 20 // 连接打开 21 SOCKET_ONOPEN(state, event) { 22 main.config.globalProperties.$socket = event.currentTarget; 23 state.socket.isConnected = true; 24 // 连接成功时启动定时发送心跳消息,避免被服务器断开连接 25 state.socket.heartBeatTimer = setInterval(() => { 26 const message = "心跳消息"; 27 state.socket.isConnected && 28 main.config.globalProperties.$socket.sendObj({ 29 code: 200, 30 msg: message 31 }); 32 }, state.socket.heartBeatInterval); 33 }, 34 // 连接关闭 35 SOCKET_ONCLOSE(state, event) { 36 state.socket.isConnected = false; 37 // 连接关闭时停掉心跳消息 38 clearInterval(state.socket.heartBeatTimer); 39 state.socket.heartBeatTimer = 0; 40 console.log("连接已断开: " + new Date()); 41 console.log(event); 42 }, 43 // 发生错误 44 SOCKET_ONERROR(state, event) { 45 console.error(state, event); 46 }, 47 // 收到服务端发送的消息 48 SOCKET_ONMESSAGE(state, message) { 49 state.socket.message = message; 50 }, 51 // 自动重连 52 SOCKET_RECONNECT(state, count) { 53 console.info("消息系统重连中...", state, count); 54 }, 55 // 重连错误 56 SOCKET_RECONNECT_ERROR(state) { 57 state.socket.reconnectError = true; 58 } 59 }, 60 modules: {} 61});
你也可以自定义mutations
中自定义websocket的默认监听事件名。
1// mutation-types.ts 2const SOCKET_ONOPEN = '✅ Socket connected!' 3const SOCKET_ONCLOSE = '❌ Socket disconnected!' 4const SOCKET_ONERROR = '❌ Socket Error!!!' 5const SOCKET_ONMESSAGE = 'Websocket message received' 6const SOCKET_RECONNECT = 'Websocket reconnected' 7const SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..' 8 9export { 10 SOCKET_ONOPEN, 11 SOCKET_ONCLOSE, 12 SOCKET_ONERROR, 13 SOCKET_ONMESSAGE, 14 SOCKET_RECONNECT, 15 SOCKET_RECONNECT_ERROR 16} 17 18// store.ts 19import { createStore } from "vuex"; 20import main from "../main"; 21import { 22 SOCKET_ONOPEN, 23 SOCKET_ONCLOSE, 24 SOCKET_ONERROR, 25 SOCKET_ONMESSAGE, 26 SOCKET_RECONNECT, 27 SOCKET_RECONNECT_ERROR 28} from "./mutation-types" 29 30export default createStore({ 31 state: { 32 socket: { 33 isConnected: false, 34 message: '', 35 reconnectError: false, 36 } 37 }, 38 mutations: { 39 [SOCKET_ONOPEN](state, event) { 40 state.socket.isConnected = true 41 }, 42 [SOCKET_ONCLOSE](state, event) { 43 state.socket.isConnected = false 44 }, 45 [SOCKET_ONERROR](state, event) { 46 console.error(state, event) 47 }, 48 // default handler called for all methods 49 [SOCKET_ONMESSAGE](state, message) { 50 state.socket.message = message 51 }, 52 // mutations for reconnect methods 53 [SOCKET_RECONNECT](state, count) { 54 console.info(state, count) 55 }, 56 [SOCKET_RECONNECT_ERROR](state) { 57 state.socket.reconnectError = true; 58 } 59 }, 60 modules: {} 61}); 62 63// main.ts 64import store from './store' 65import { 66 SOCKET_ONOPEN, 67 SOCKET_ONCLOSE, 68 SOCKET_ONERROR, 69 SOCKET_ONMESSAGE, 70 SOCKET_RECONNECT, 71 SOCKET_RECONNECT_ERROR 72} from './mutation-types' 73 74const mutations = { 75 SOCKET_ONOPEN, 76 SOCKET_ONCLOSE, 77 SOCKET_ONERROR, 78 SOCKET_ONMESSAGE, 79 SOCKET_RECONNECT, 80 SOCKET_RECONNECT_ERROR 81} 82 83app.use(VueNativeSock,"",{ 84 store: store, 85 mutations: mutations 86});
在main.js | main.ts
中导入pinia
的配置文件。
1// useSocketStore为pinia的socket配置文件 2import { useSocketStoreWithOut } from './useSocketStore'; 3 4const store = useSocketStoreWithOut(); 5 6app.use(VueNativeSock, "", { 7 store: store 8});
我专门写了一个demo用来演示pinia的集成,如果你需要参考的话请移步:pinia-websocket-project
pinia的socket配置文件代码如下:
1import { defineStore } from 'pinia'; 2import { store } from '/@/store'; 3import main from '/@/main'; 4 5interface SocketStore { 6 // 连接状态 7 isConnected: boolean; 8 // 消息内容 9 message: string; 10 // 重新连接错误 11 reconnectError: boolean; 12 // 心跳消息发送时间 13 heartBeatInterval: number; 14 // 心跳定时器 15 heartBeatTimer: number; 16} 17 18export const useSocketStore = defineStore({ 19 id: 'socket', 20 state: (): SocketStore => ({ 21 // 连接状态 22 isConnected: false, 23 // 消息内容 24 message: '', 25 // 重新连接错误 26 reconnectError: false, 27 // 心跳消息发送时间 28 heartBeatInterval: 50000, 29 // 心跳定时器 30 heartBeatTimer: 0, 31 }), 32 actions: { 33 // 连接打开 34 SOCKET_ONOPEN(event) { 35 main.config.globalProperties.$socket = event.currentTarget; 36 this.isConnected = true; 37 // 连接成功时启动定时发送心跳消息,避免被服务器断开连接 38 this.heartBeatTimer = window.setInterval(() => { 39 const message = '心跳消息'; 40 this.isConnected && 41 main.config.globalProperties.$socket.sendObj({ 42 code: 200, 43 msg: message, 44 }); 45 }, this.heartBeatInterval); 46 }, 47 // 连接关闭 48 SOCKET_ONCLOSE(event) { 49 this.isConnected = false; 50 // 连接关闭时停掉心跳消息 51 window.clearInterval(this.heartBeatTimer); 52 this.heartBeatTimer = 0; 53 console.log('连接已断开: ' + new Date()); 54 console.log(event); 55 }, 56 // 发生错误 57 SOCKET_ONERROR(event) { 58 console.error(event); 59 }, 60 // 收到服务端发送的消息 61 SOCKET_ONMESSAGE(message) { 62 this.message = message; 63 }, 64 // 自动重连 65 SOCKET_RECONNECT(count) { 66 console.info('消息系统重连中...', count); 67 }, 68 // 重连错误 69 SOCKET_RECONNECT_ERROR() { 70 this.reconnectError = true; 71 }, 72 }, 73}); 74 75// Need to be used outside the setup 76export function useSocketStoreWithOut() { 77 return useSocketStore(store); 78}
为了方便在组件外面使用pinia,这里额外导出了useSocketStoreWithOut
,否则pinia会报错,提示找不到pinia实例。
pinia的store配置代码如下:
1import type { App } from 'vue'; 2import { createPinia } from 'pinia'; 3 4const store = createPinia(); 5 6export function setupStore(app: App<Element>) { 7 app.use(store); 8} 9 10export { store };
下述方法,均为插件的可传参数,可以和
store
搭配使用
1{ 2 "protocol": "my-protocol" 3}
1{ 2 "format": "json" 3}
如果你没启用JSON消息传递,只能使用
send
方法来发送消息.
reconnection
,启用时可配置重连次数reconnectionAttempts
与重连间隔时长reconnectionDelay
1{ 2 "reconnection": true, 3 "reconnectionAttempts": 5, 4 "reconnectionDelay": 3000 5}
1{ 2 "connectManually": true 3}
启用手动管理连接后,项目启动时则不会自动连接,你可以在项目的特定组件调用连接方法来进行连接。在组件销毁时调用关闭方法来关闭连接。
如果你启用了手动连接,必须要要启用vuex,否则此设置将不会生效。
1 // 连接websocket服务器,参数为websocket服务地址 2 this.$connect(""); 3 // 关闭连接 4 this.$disconnect(); 5 6 // CompositionAPI 7 proxy.$connect(""); 8 proxy.$disconnect("");
passToStoreHandler
参数即可,如果你没有传则走默认的处理函数,默认函数的定义如下:1export default class { 2 /** 3 * 默认的事件处理函数 4 * @param eventName 事件名称 5 * @param event 事件 6 */ 7 defaultPassToStore( 8 eventName: string, 9 event: { 10 data: string; 11 mutation: string; 12 namespace: string; 13 action: string; 14 } 15 ): void { 16 // 事件名称开头不是SOCKET_则终止函数 17 if (!eventName.startsWith("SOCKET_")) { 18 return; 19 } 20 let method = "commit"; 21 // 事件名称字母转大写 22 let target = eventName.toUpperCase(); 23 // 消息内容 24 let msg = event; 25 // data存在且数据为json格式 26 if (this.format === "json" && event.data) { 27 // 将data从json字符串转为json对象 28 msg = JSON.parse(event.data); 29 // 判断msg是同步还是异步 30 if (msg.mutation) { 31 target = [msg.namespace || "", msg.mutation].filter((e: string) => !!e).join("/"); 32 } else if (msg.action) { 33 method = "dispatch"; 34 target = [msg.namespace || "", msg.action].filter((e: string) => !!e).join("/"); 35 } 36 } 37 if (this.mutations) { 38 target = this.mutations[target] || target; 39 } 40 // 触发store中的方法 | Trigger the method in the store 41 if (this.store._p) { 42 // pinia 43 target = eventName.toUpperCase(); 44 this.store[target](msg); 45 } else { 46 // vuex 47 this.store[method](target, msg); 48 } 49 } 50}
当你要自定义一个函数时,这个函数接收3个参数:
下面是一个例子
1app.use(VueNativeSock, "", { 2 passToStoreHandler: function (eventName, event, next) { 3 event.data = event.should_have_been_named_data 4 next(eventName, event) 5 } 6})
send
发送非json类型的数据(使用插件时不能启用JSON消息传递)sendObj
发送json类型的数据(必须在使用插件时启用JSON消息传递)$connect
连接websocket服务器(必须在使用插件时启用手动管理连接选项)onmessage
收到服务端推送消息时的监听$disconnect
断开websocket连接注意:上述方法均支持在optionsAPI与CompositionAPI中使用,具体的用法请查阅相关函数的文档。
做完上述配置后,就可以在组件中使用了,如下所示为发送数据的例子。
1export default defineComponent({ 2 methods: { 3 clickButton: function(val) { 4 // 调用send方法,以字符串形式发送数据 5 this.$socket.send('some data'); 6 // 如果fomat配置为了json,即可调用sendObj方法来发送数据 7 this.$socket.sendObj({ awesome: 'data'} ); 8 } 9 } 10})
注意:
sendObj
方法必须在你启用JSON消息传递时才可以使用,不然只能使用send
方法。
消息监听,即接收websocket服务端推送的消息,如下所示为消息监听的示例代码。
1// optionsAPI用法 2this.$options.sockets.onmessage = (res: { data: string }) => { 3 console.log(data); 4} 5 6// CompositionAPI用法 7import { getCurrentInstance } from "vue"; 8const { proxy } = getCurrentInstance() as ComponentInternalInstance; 9proxy.$socket.onmessage = (res: { 10 data: string; 11}) => { 12 console.log(data); 13}
发送消息,向服务端推送消息
1// optionsAPI用法 2this.$socket.sendObj({msg: '消息内容'}); 3 4// compositionAPI写法 5const internalInstance = data.currentInstance; 6internalInstance?.proxy.$socket.sendObj({ 7 msg: "消息内容" 8});
compositionAPI写法由于在setup中无法拿到vue实例,因此需要在页面挂载后将实例存储到全局对象中,用的时候再将实例取出来。详细使用方法可以参考我的chat-system中的写法:InitData.ts#L91 、EventMonitoring.ts#L50 、SendMessage.ts#L73 、contact-list.vue#L620
移除消息监听
1delete this.$options.sockets.onmessage 2// compositionAPI写法 3delete proxy.$socket.onmessage
至此,插件的所有使用方法就介绍完了。
想进一步了解插件源码的请移步项目的GitHub仓库:vue-native-websocket-vue3
Vue2版本请移步原插件:vue-native-websocket
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
Found 3/22 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
license file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
69 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-03-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More