VueJS + Django频道

fir*_*ter 17 python django vue.js django-channels

我刚刚阅读了VueJSDjango频道的介绍,并希望将它们结合使用,为网页上的几个组件提供实时更新.这说明了基本思想:

在此输入图像描述

作为VueJS的新手,上面的图表似乎需要在VueJS组件和websocket之间使用某种类型的"中间人",以确保每个组件都能获得正确的数据.

所以,我的问题是:

  1. 在建筑方面,这是一个很好的设计吗?
  2. 如果是这样,VueJS可以作为那个"中间人"来管理哪个组件连接到哪个频道?

谢谢你的帮助 :)

pea*_*man 20

不,你不需要一个中间人.但是你可以(通过频道进行大量更新)使用Vuex并使用套接字数据提供更好的功能.然后,如果所有内容都正确连接,您的Vue应用程序将只是视图层,它会对更改做出反应(没有双关语).

Django频道只是队列(先进先出).您将需要发送的任何数据传递到前端到通道.所有数据都被序列化并传递给队列.通道处于工作模式,一旦收到消息(带有数据),它就会尝试在它自己的通道上发出它.

如何在Vue中收集这些数据?

我做的是设置Vuex.然后,我制作了一个名为Vuex的插件createWebSockets.js.当您浏览Vuex和Vuex插件的文档时,您会看到该插件可以访问Vuex commit方法.在我说的插件中,我打开了套接字到我在服务器上运行的通道,每当有新消息通过时,我只是推送了Vuex中的数据,而我的Vue应用程序只是对这些更改做出了反应.

如果您需要更多帮助,我可能会在某个地方找到它.

最好

编辑

因此,在熟悉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
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是你如何通过套接字更新Vuex.

希望能帮助到你.

  • 嗯。确实,有人工智能和机器学习的开源实现。但是没有简单的方法可以使用来自 Meteor 以外的后端的推送通知...... Grrrr。 (2认同)