VueVuex中的Web套接字(如何从服务器接收排放)

问题描述 投票:0回答:1

所以直到现在,我只是在Vue组件中的socket.io-client与WebSocket进行通信,现在我将Vuex添加到项目中,并声明了一个Websocket,就像这样

Vue.use(new VueSocketIO({
  debug: true,
  connection: 'http://192.168.0.38:5000',
}));

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

1) 我现在应该在组件本身还是在商店里发出一些消息之类的东西?

2) 在我引入这些变化之前,我可以做这样的事情。

socket.on('connect', function () {
      console.error('connected to webSocket');
      socket.emit('my event', { data: 'I\'m connected!' });
    });

socket.on('my response', function(data){
      console.log('got response');
      console.log(data.data);
    });

当发送 "我的事件 "时,flask服务器会用 "我的响应 "来回应。现在我在改变后从一个组件中尝试同样的事情,就像这样。

    this.$socket.emit('my_event', { data: 'I\'m connected!' });
    console.error('send to websocket ');

    this.$options.sockets.my_event = (data) => {
      console.error('received answer ');
      console.error(data);
    };

my_event到达了我的flask服务器,但是我没有得到响应接收的工作。我到底做错了什么?另外,因为我在问我是应该把这个放在组件里还是放在商店里,所以我发现商店里有这样的东西。

SOCKET_MESSAGECHANNEL(state, message) {
      state.socketMessage = message
    }

解释是 "比如说,如果你的频道叫messageChannel,相应的Vuex突变就是SOCKET_MESSAGECHANNEL",它来自这个网站 https:/alligator.iovuejsvue-socketio。.

我想我现在还不太明白什么是通道。我从flask服务器发出的my_response也是一个channel吗?先谢谢你的帮助!

EDIT: 所以现在我试图从我的商店监听和发射到websocket。为此,我尝试了以下内容。在main.js中,我有这个部分。

Vue.use(new VueSocketIO({
  debug: true,
  connection: SocketIO('http://192.168.0.38:5000'),
  vuex: {
    store,
    actionPrefix: 'SOCKET_',
    mutationPrefix: 'SOCKET_',
  },
}));

然后在我的store.js中我有以下内容。

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
    title: 'title from vuex store',
    isConnected: false,
  },
  mutations: {
    increment(state) {
      state.count += 1;
    },
    emitSth(state) {
      this.sockets.emit('my_event', { data: 'I\'m connected!' });
      console.log(state.count);
    },
    SOCKET_my_response(state) {
      state.isConnected = true;
      alert(state.isConnected);
    },
    SOCKET_connect(state) {
      state.isConnected = true;
      alert(state.isConnected);
    },
  },
});

在我的组件中,我有这个脚本。

export default {
  name: 'ControlCenter',
  data() {
    return {
      devices: [{ ip: 'yet unknown' }], // placeholder so line 12 does not throw error before actual device info fetched
      thisDeviceIndex: 0,
      currentLayoutIndex: 0,
      layouts: [],
    };
  },
  computed: mapState([
    'title',
    'count',
  ]),
  components: {
    DNDAssign,
    FirstPage,
  },
  methods: {
    // mapMutation helper let's us use mutation from store via this instead of this.$store
    ...mapMutations([
      'increment',
      'emitSth',
    ]),
    incrementMutation() {
      this.increment();
    },
    emitEvent() {
      this.emitSth();
    },
    // some other stuff here
  },
  created() {
    // inital fetching of layouts
    console.log('fetching layouts from backend');
    this.getAllLayouts();

    console.log(this.$socket);
  },
};

我也有一个触发发射的按钮,它是:

<b-button
type="button"
variant="success"
v-on:click="emitEvent()"
>
emit event
</b-button>

商店里的连接被触发。然而,我得到了以下的错误,对于发出的:

  • "TypeError.Cannot read property 'emit' of undefined 无法读取未定义的'emit'属性"
  • "无法读取未定义的'发射'属性"

另外我对突变中的命名也不清楚。如果我有这个mutationPrefix。难道不应该使用connect代替SOCKET_connect吗?

javascript vue.js socket.io vuex
1个回答
0
投票

首先,如果你使用的是Vue-Socket.io 3.0.5>版本,请卸载它并安装3.0.5版本。

npm uninstall vue-socket.io
npm install [email protected]

然后将版本锁定在 packege.json: "vue-socket.io": "3.0.5"最新的更新似乎破坏了图书馆,阅读更多信息。此处

现在要从socket.io服务器接收事件,你可以这样做。

this.sockets.subscribe("my response", (data) => {
    console.log(data);
});

或者如果你想把监听器放在组件层,你需要在组件层添加 sockets 例如,在组件导出中使用Vuex对象。

export default {
    ...
    sockets: {
        "my response": function (data) {
            console.log(data);
        }
    }
    ...
}

由于你没有在VueSocketIO上使用Vuex集成,所以你不需要在存储突变中添加额外的功能。如果您想在VueSocketIO上使用Vuex集成,您需要在VueSocketIO上添加以下功能 vuex 对象,同时声明VueSocketIO类。

下面是一个基本的例子 main.js

// Set Vue to use Vuex
Vue.use(Vuex);

// Create store
const store = new Vuex.Store({
  state: {
      someData: null
  },
  getters: {},
  actions: {
      "SOCKET_my response"(context, data) {
          // Received `my response`, do something with the data, in this case we are going to call mutation "setData"
        context.commit("setData", data);
      }
  }
  mutations: {
      ["setData"](state, data) {
          state.someData = data; // Set it to state
      }
  }
});

// Set Vue to use VueSocketIO with Vuex integration
Vue.use(new VueSocketIO({
  debug: true,
  connection: 'http://192.168.0.38:5000',
  vuex: {
      store,
      actionPrefix: "SOCKET_"
    }
}));

new Vue({
  router,
  store
  render: h => h(App)
}).$mount("#app");

如果你需要Vuex集成的例子,你可以查看 我的示例应用 使用Vue和Vue-Socket.io与Vuex integration.te的。

© www.soinside.com 2019 - 2024. All rights reserved.