Dealing with asynchronous operations in Vue has been a challenge for me. Coming from a C# background, I find the async-await pattern more intuitive than in JavaScript or TypeScript, especially when working with Vue.
I have two components set up without using Vuex:
// App.vue
// ...
async beforeCreated() {
console.log('connecting')
await WebSocket.connect(...)
console.log('connected')
}
// ChildComponent.vue
// ...
async mounted() {
console.log('invoking')
await WebSocket.Invoke(...)
console.log('invoked')
}
The output I'm getting is as follows:
1. connecting
2. invoking
3. invoked
4. connected
This means that I am not properly connected and the Invoke operation fails. I've attempted using Vuex but without success. While connecting to the WebSocket is straightforward by using Actions and Mutations, the 'Invoking' part is where I struggle.
In an attempt to address this, I tried the following code snippet only to receive undefined
:
// ChildComponent.vue
// ...
async mounted() {
await this.$store.state.moduleA.webSocket.Invoke(...) // moduleA is defined but webSocket is not
}
Furthermore, utilizing Vuex's mutations and actions feels illogical since I'm simply calling a server-side procedure without changing the state of any object.
How should I properly implement this? I'm currently stuck on this issue and could use some guidance. It's worth noting that I am working with TypeScript.
HTML code for Vue components:
App.vue
<template>
<child-component />
</template>
<script lang="ts">
import ChildComponent from './components/ChildComponent.vue';
export default Vue.extend({
components: { ChildComponent },
name: 'App',
async beforeCreate() {
await this.$WebSocket.connect(...)
}
});
</script>
ChildComponent.vue
<template>
<div>something</div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
name: 'ChildComponent',
async mounted(): Promise<void> {
await this.$WebSocket.Invoke(...)
},
})
</script>