VueJS+Django频道

2024-10-01 09:40:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚读完了VueJSDjango Channels的介绍,我想把它们一起使用,为网页上的几个组件提供实时更新。这说明了基本思想:

enter image description here

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

所以,我的问题是:

  1. 从建筑上讲,这是一个好的设计吗?在
  2. 如果是这样,VUEJ是否可以充当“中间人”来管理哪个组件连接到哪个通道?在

感谢您的帮助:)


Tags: 数据django网页类型图表组件websocket思想
1条回答
网友
1楼 · 发布于 2024-10-01 09:40:21

不,你不需要中间人。但是,您可以(如果通过通道有很多更新)更好地使用Vuex并向它提供套接字数据。如果一切都连接正确,你的Vue应用程序将只是视图层,对更改做出反应(没有双关语)。在

Django通道只是队列(先进先出)。你可以把你需要发送到前端的任何数据传递给通道。所有数据被序列化并传递到队列。通道处于工作模式,一旦它接收到一条消息(包含数据),它就会尝试在它自己的通道上发出消息。在

如何在Vue中获取这些数据?在

我所做的就是建立Vuex。然后我制作了一个名为createWebSockets.js的Vuex插件。当你浏览Vuex和Vuex插件的文档时,你会看到这个插件可以访问Vuexcommit方法。在这个插件中,我打开了我在服务器上运行过的频道的套接字,每当有新消息通过时,我就在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
    }
}

这就是通过套接字更新Vuex的方法。在

希望有帮助。在

相关问题 更多 >