我刚刚读完了VueJS和Django Channels的介绍,想把它们结合起来,为网页上的几个组件提供实时更新.这说明了基本思想:
作为VueJS新手,上面的图表似乎需要在VueJS组件和websocket之间进行某种类型的"中间人",以确保每个组件获得正确的数据.
所以,我的问题是:
- 在建筑上,这是一个好的设计吗?
- 如果是这样,VueJS能否充当"中间人"来管理哪个组件连接到哪个通道?
谢谢你的帮助:)
我刚刚读完了VueJS和Django Channels的介绍,想把它们结合起来,为网页上的几个组件提供实时更新.这说明了基本思想:
作为VueJS新手,上面的图表似乎需要在VueJS组件和websocket之间进行某种类型的"中间人",以确保每个组件获得正确的数据.
所以,我的问题是:
谢谢你的帮助:)
不,你不是中间人.但你可以(如果有很多更新通过通道)更好地使用Vuex,并为其提供套接字数据.然后,如果一切都连接正确,你的Vue应用程序将只是对更改做出react 的视图层(没有双关语).
Django频道只是队列(先进先出).您可以将需要发送到前端的任何数据传递到通道.所有数据都被序列化并传递到队列.通道处于工作模式,一旦收到消息(带有数据),它就会try 在自己的通道上发出消息.
如何在Vue中获取这些数据?
我所做的是设置Vuex.然后我制作了一个名为createWebSockets.js
的Vuex插件.当你浏览Vuex和Vuex插件的文档时,你会看到该插件可以访问Vuex commit
方法.在上述插件中,我打开了服务器上运行的频道的套接字,每当收到新消息时,我就在Vuex中推送数据,我的Vue应用程序就对这些更改做出react .
如果你需要更多的帮助,我可能会在某个地方找到它.
最好的
Edit
因此,在您熟悉Vuex并将其添加到应用程序后,您可以执行以下操作:
//插件代码
// 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的方式.
希望有帮助.