When foo() is completed, I need to choose one of bar1(), bar2(), or bar3() as the actual function to be sent to the web socket and store the callback value in vuex.
1. bar1(): If I include bar1() in the onMounted scope, it does not work and the store becomes undefined.
2. bar2(): Passing the argument "store" into bar2() in XXX.vue makes it work successfully.
3. bar3(): Surprisingly, even if bar3() is not in the onMounted scope, it still works without waiting for foo() to complete, which is not the expected behavior.
The msg_state stores something in store.state and I want to commit it to update its value.
Questions:
- What sets bar1(), bar2(), and bar3() apart from each other?
- Why does bar2() work as bar() while bar1() does not?
- Is the success of bar3() due to it being inside the setup() scope rather than the onMounted() scope?
// In socket.js
// Does not work
import { useStore } from 'vuex'
export const bar1 = async(input) => {
// store is undefined
const store = useStore()
socket = io(url)
socket.on('message', (msg) = {
// commit is not defined
store.commit("msg_state", msg)
})
}
// Works
export const bar2 = async(input, store) => {
socket = io(url)
socket.on('message', (msg) = {
store.commit("msg_state", msg)
})
}
// Works but not asynchronous
import { useStore } from 'vuex'
export const bar3 = (input) => {
const store = useStore()
socket = io(url)
socket.on('message', (msg) = {
store.commit("msg_state", msg)
})
}
//In XXX.vue
import bar from '@/util/socket.js'
...
export default {
setup() {
const xxx = reactive({input: oldVal})
const store = useStore()
onMounted(async () => {
//{input: oldVal}
await foo()
//{input: newVal}
// option1: bar1 as bar
await bar1(xxx.input) // counldn't work
// option2: bar2 as bar
await bar2(xxx.input, store) // this could work
})
// option3: bar3 as bar
bar3(xxx.input) // this could work but not async
}
}