I have a Vue component that is rendered on a route like this:
{
path: '/chat/:Username(\w+)?',
name: 'ViewChat',
component: Chat
}
The Chat.vue
component should render at the path /chat
and also /chat/michael
for example.
However I lose my ref
data when I go from /chat
to /chat/michael
which I don’t understand why when the component is supposed to be reused.
This what I mean in Chat.vue
component (code reduced for brevity):
<template>
<button @click="openMessages('michael')">Open messages</button>
<div v-if="ShowMessages">
<h1>Your messages</h1>
</div>
</template>
<script>
setup() {
const ShowMessages = ref();
function openMessages(Username){
await VueRouter.push({name: 'Chat', params:{Username: Username}});
const SelectedUsername = Username;
ShowMessages.value = true;
console.log(ShowMessages.value) // Shows true but appears as undefined in Vue dev tools
console.log(SelectedUsername) // Shows 'michael' which means the code ran after route change
}
return {
ShowMessages,
openMessages
}
}
</script>
The HTML to be rendered for ShowMessages
being true
doesn’t work because Vue thinks it is undefined
. It will only work if I remove the line:
await VueRouter.push({name: 'Chat', params:{Username: Username}});
Why would the code for setting the SelectedUsername
and ShowMessage.value
variables run but show as undefined
in Vue devtools and so never work? The only way around it is to use a store
but why should I use a store for simple variables in a reusable component?
3