After setting up a basic Vue project with the vue-cli tool using vue init webpack my-project
, I encountered an issue with sending information through a web socket before the page renders. To keep this logic separate from the Vue component, I created a separate JavaScript file named ws.js
. Here's the code snippet based on this:
import Vue from 'vue'
const websocket = new WebSocket('ws://localhost:1234')
const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
websocket.send(JSON.stringify(message))
}
}
})
export default emitter
When attempting to utilize the emitter
object to transmit information upon page load in my Vue component:
<template>
<div class="hello">
TEST
</div>
</template>
<script>
import emitter from '../ws/ws'
export default {
name: 'HelloWorld',
beforeMount () {
emitter.send('Hello')
}
}
</script>
An error surfaced in the Firefox console:
[Vue warn]: Error in beforeMount hook: "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable"
found in
---> at src/components/HelloWorld.vue at src/App.vue
I'm puzzled by this error. Is my approach correct? Should I consider attaching the functionality to a different event listener rather than beforeMount()
? Interestingly, when I disable the WebSocket related lines, the error vanishes:
import Vue from 'vue'
// const websocket = new WebSocket('ws://localhost:1234')
const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
// websocket.send(message)
}
}
})
export default emitter