gpt4 book ai didi

vue.js - 如何使用 websocket 突变组织 vuex

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:08 25 4
gpt4 key购买 nike

我用的是vue+vuex+vue-native-websocket。根据使用 vuex 处理 websocket 消息的文档,我应该使用 SOCKET_... 突变。

目前我处理store/index.js 文件中的所有消息,如下所示:

mutations: {
...
SOCKET_ONMESSAGE(): {
switch(message.cmd) {
case 'userRsp'
...
case 'connectionRsp'
...
case 'otherDataRsp'
etc.
}
}

我想要的是在user.js vuex 模块中处理所有与用户相关的数据,在connections.js vuex 模块中处理所有连接数据。

我应该在每个组件中使用 SOCKET_ONMESSAGE 吗?在这种情况下,根据我的测试,ON_MESSAGE 将被调用,即使是消息不是针对该模块的。

最佳答案

vue-native-websocket readme :

With format: 'json' enabled

[...]

If there is a .namespace on the data, the message is sent to this namespaced: true store (be sure to turn this on in the store module).

If there is a .mutation value in the response data, the corresponding mutation is called with the name SOCKET_[mutation value]

If there is an .action value in the response data ie. action: 'customerAdded', the corresponding action is called by name:

actions: {
customerAdded (context) {
console.log('action received: customerAdded')
}
}

当使用 json 格式选项时:

Vue.use(VueNativeSock, 'ws://localhost:9090', { format: 'json' })

然后您可以在响应中传递 namespacemutationaction 名称,它将在您的商店模块中调用正确的函数。

Does it mean that the backend should insert namespace property to the response?

是的。例如。后端应在数据中发送namespace: "user" 以调用同名模块。


isn't it a bad practice when the backend defines the handler in frontend who should handle the message?

您的后端是否打算供多个应用程序使用?那些不是你自己 build 的?如果不是,则后端和前端是同一个应用程序。

您可以通过仅传递 namespace 属性并让前端处理它来避免在后端过于冗长,但也可以更容易地告诉操作。这些是通用属性名称,因此不会太耦合。

关于vue.js - 如何使用 websocket 突变组织 vuex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49629494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com