In my Vue.js (2.x) app I have a component that represents a mailbox, i.e. displays a list of messages. The component's route is defined thus:
{
path: '/messages/:messageId',
name: 'messages',
component: Messages,
// this sets the component's messageId prop to the same value as the route param
props: true
}
When the component is created, the messages are loaded from the server. If the messageId route param is specified, the message with this ID will be selected initially
props: {
messageId: {
type: String,
required: false,
default: null
}
},
data () {
return {
allMessages: [],
selectedMessage: null
}
},
async created () {
this.allMessages = await messageService.loadMessages()
if (this.messageId) {
this.selectedMessage = this.allMessages.find(message => message.id == this.messageId);
}
}
When the user clicks on a message, selectedMessage is updated. I would also like to update the messageId route param such that the user could (for example)
However, I'm not sure how to update the route param when the selected message changes? I guess I could do something like
methods: {
onMessageSelected (selectedMessage) {
this.selectedMessage = selectedMessage
const params = { messageId: selectedMessage.id }
this.$router.push({ name: 'messages', params: params } })
}
}
But this reloads the whole route/component, causing the list of messages to be fetched again, which is very inefficient. Is there a way to just update the route param in the URL without reloading the route/component?
I think that you could try:
this.$router.push({ name: 'messages', params: params } })
Or
this.$router.push({ path: `/messages/${messageId}`})