【问题标题】:Vue: Using the Vuex store in a JS classVue:在 JS 类中使用 Vuex 存储
【发布时间】:2020-11-17 05:03:33
【问题描述】:

我有一个 Vue 应用程序,我在其中使用 Socket.io 进行实时连接。我决定将所有 Socket 调用放入它自己的 socket.js 类中,并将该类导入到我的 Vue 组件中。我已经导入了商店,但我希望能够在这个 js 文件中将数据保存到 Vuex 商店,但我不知道如何在 .vue 文件之外执行此操作。

AppSocketIO.js

import store from '../../../store';

class AppSocketIO {
    init() {
        this.socketIO = new AppSocketIO('kjiu887', {
          // run a mutation to save data to the Vuex store
        });
    }

VueComponent

mounted() {
    this.initSocket();
},
methods: {
    initSocket: function() {
        const socket = new AppSocketIO();
    }
}
    

【问题讨论】:

    标签: vuejs2 vuex


    【解决方案1】:

    这就是我会做的。将套接字保留在单独的文件中。

    socket.on('message', (data) => {
      store.commit('mutationName', data) // For mutations
      store.dispatch('actionName', data) // For actions
    })
    

    如果您的变更/操作是命名空间的,您必须牢记这一点。

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2019-09-09
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2021-05-31
      • 2020-01-11
      • 2021-07-25
      • 1970-01-01
      相关资源
      最近更新 更多