Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Vuex with Nuxt and Vue-Native-Websocket

I'm trying to fill my vuex store with data from websocket. I'm using Nuxt. For handling websocket I'm using vue-native-websocket package. Connection to websocket is successful, but commiting to the store doesn't work, it fires an error on every socket event Uncaught TypeError: this.store[n] is not a function

According to Nuxt and vue-native-websocket docs, I've using them as following:

Plugin native-websocket.js:

import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
import store from '~/store'

Vue.use(VueNativeSock, 'wss://dev.example.com/websocket/ws/connect', { store: store })

nuxt.config.js

  plugins: [
   {src: '~plugins/native-websocket.js', ssr: false}
],

As the connection is established, I draw a conclusion that the package is connected right, so it's something about store and I can't get what's wrong

UPD: After some workaround I've found out that logging store inside native-websocket.js returns

store() {
  return new __WEBPACK_IMPORTED_MODULE_1_vuex__["default"].Store({
   state: {...my store

and commiting to it returns __WEBPACK_IMPORTED_MODULE_2__store__.default.commit is not a function So it's something about webpack as I can see

like image 502
Elijah Ellanski Avatar asked Jul 25 '18 15:07

Elijah Ellanski


People also ask

Is there a socket Io plugin for Vue?

There is no lack of socket.io plugins for Vue. vue-socket.io looks like a good solution. However, I try to avoid 3rd party dependencies if I can easily implement their function myself, as in the case of socket.io. To reuse the socket I need to pass the same instance to Vue and the Vuex store.

How do I use nuxt route in Vue?

Nuxt.js transforms every *.vue file inside the pages directory as a route for the application. Create ./pages/index.vue inside your project. It is important that this page is called index.vue as this will be the default home page Nuxt shows when the application opens.

What is the use of Vuex?

Vuex is a state management plugin for Vue.js. It allows you to centrally store all data needed for a Vue application and manage mutations (changes) to that data. Out of the box it works really well for working with data from an API.

How to check the socket state in Vue?

You can also check the socket state directly with the this.$socket object on the main Vue object. Handle all the data in the SOCKET_ONMESSAGE mutation.


1 Answers

You need to import store differently e.g. get it from context of plugin. Here some docs, but they somewhat lacking

import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'

export default ({ store }, inject) => {
  Vue.use(VueNativeSock, 'wss://dev.example.com/websocket/ws/connect', { store: store })
}
like image 153
Aldarund Avatar answered Oct 13 '22 17:10

Aldarund