John Smith
John Smith

Reputation: 1876

Importing a Vue library in nuxt.js via plugins

Any idea how I'm going to use this plugin? https://github.com/DimanVorosh/vue-json-rpc-websocket/blob/e2199d89dc15f50e57e7c5c70adfd95e5ceb5cda/src/wsMain.js

I see that it is auto registering with vue but I can't use it in nuxt.

I created the plugins/vue-json-rpc-websocket.client.js, registered in nuxt.config.js as

'~/plugins/vue-json-rpc-websocket.client.js'

but I have no idea what to write in the inject method and IF I have to do it to make it work. this.$socket is undefined in component.

import Vue from 'vue'
import JRPCWS from 'vue-json-rpc-websocket'

Vue.use(JRPCWS, 'wss://bsc-ws-node.nariox.org:443', {
    reconnectEnabled: true,
    reconnectInterval: 5000,
    reconnectAttempts: 3
})

// do I need this?
export default ({ app }, inject) => {
    // Inject $hello(msg) in Vue, context and store.
    // inject('hello', msg => console.log(`Hello ${msg}!`))
}

also, any idea how can I ENV the 'wss://bsc-ws-node.nariox.org:443' string?

Upvotes: 2

Views: 944

Answers (1)

kissu
kissu

Reputation: 46604

Totally working on my side with the package that you're using and your given configuration. No need to inject anything so far!
Here is a fresh repo created for the example: https://github.com/kissu/so-nuxt-json-rpc-websocket

The below screenshot is using a console.log(this.$socket) in a mounted hook in /pages/index.vue but you can also use $vm0 and access the instance directly from the devtools after selecting the root component (in the screenshot too). enter image description here


For the env variables part, you can create an .env file at the root of your directory like this

WS_URL="wss://echo.websocket.org"
// nuxt.config.js
export default {
  publicRuntimeConfig: {
    wsUrl: process.env.WS_URL,
  },
}

Then, use this variable in your plugin like this

import Vue from 'vue'
import JRPCWS from 'vue-json-rpc-websocket'

export default ({ $config: { wsUrl } }) => {
  Vue.use(JRPCWS, wsUrl, {
    reconnectEnabled: true,
    reconnectInterval: 5000,
    reconnectAttempts: 3
  })
}

Upvotes: 3

Related Questions