// importing from node_modules -> you have to install it
// through npm or yarn
import io from 'socket.io-client'
// opening a socket to an IP. Mind that I've put an
// example IP here yours will be an IP belonging to the
// server or 127.0.0.1 if you're working locally
const socket = io('127.0.0.1:4000')
// this is a vuex plugin that takes the store (vuex store)
// object as its parametar
export default function createWebSockets(socket) {
// it returns a function to which we passed store object
return (store) => {
// this is your channel name on which you want to
// listen to emits from back-end
const channel_name = 'whatever-you-called-it'
// this opens a listener to channel you named on line above
socket.on('channel_name', (data) => { //
// and this is the store part where you
// just update your data with data received from socket
store.commit('YOUR_VUEX_MUTATION', data)
})
// you can add multiple socket.on statements if you have more than one channel
}
}
不,你不需要中间人。但是,您可以(如果通过通道有很多更新)更好地使用Vuex并向它提供套接字数据。如果一切都连接正确,你的Vue应用程序将只是视图层,对更改做出反应(没有双关语)。在
Django通道只是队列(先进先出)。你可以把你需要发送到前端的任何数据传递给通道。所有数据被序列化并传递到队列。通道处于工作模式,一旦它接收到一条消息(包含数据),它就会尝试在它自己的通道上发出消息。在
如何在Vue中获取这些数据?在
我所做的就是建立Vuex。然后我制作了一个名为
createWebSockets.js
的Vuex插件。当你浏览Vuex和Vuex插件的文档时,你会看到这个插件可以访问Vuexcommit
方法。在这个插件中,我打开了我在服务器上运行过的频道的套接字,每当有新消息通过时,我就在Vuex中推送数据,我的Vue应用程序就对这些更改做出反应。在如果你需要更多的帮助,我可以在某处找到它。在
最佳
编辑
因此,在您熟悉Vuex并将其添加到应用程序后,您可以执行以下操作:
//插件代码
这就是通过套接字更新Vuex的方法。在
希望有帮助。在
相关问题 更多 >
编程相关推荐