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

enter image description here

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

所以,我的问题是:

  1. 在建筑上,这是一个好的设计吗?
  2. 如果是这样,VueJS能否充当"中间人"来管理哪个组件连接到哪个通道?

谢谢你的帮助:)

推荐答案

不,你不是中间人.但你可以(如果有很多更新通过通道)更好地使用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的方式.

希望有帮助.

Vue.js相关问答推荐

在VueJS中卸载元素之前是否应该删除JavaScript事件收件箱?

VueJS不会呈现一个名为None的组件""

vue3 + pinia:如何从?store 中获取一个值

带有参数的 Vuex 映射 Getter - 缓存?

即使响应为 200,也会调用 Axios Catch

在 jest document.querySelector 中测试 vue 组件期间始终返回 null

是否可以在没有 Vue 的情况下使用 Vuex?

Vuetify - 如何保持第一个扩展面板默认打开,如果我打开另一个面板,其他面板应该关闭?

Vue.js 从模板中分离样式

全局方法和实例方法有什么区别?

ECMA6 中 nameFunction() {} 和 nameFunction () => {} 的区别

Angular 5 中的 功能

为什么我在 vue.js 中得到避免使用 JavaScript 一元运算符作为属性名称?

Vue 组件 Vue-Instant

如何从 vue 组件调用 App.vue 中的方法

VueJS错误避免直接改变props

如何在 vue.js 中进行嵌入?

使用 Vue 的点击编辑文本字段

Vuejs 组件等待 facebook sdk 加载

将它们分开时将 Django 的 csrf_token 放入 Vuejs