Home » vue » Vuejs router listen to events

Vuejs router listen to events

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a component wherein the props were passed through the route (https://router.vuejs.org/guide/essentials/passing-props.html). My question is how do I listen to emitted events from the component so that I can mutate the props passed from the route?

In my route I have something like

...
{
    path: "details/:id?",
    name: "booking.details",
    component: BookingDetails,
    props: true
}
...

And inside the component I have a props

...
props: {
    invoice: {
        type: Object,
        required: false,
        default: () => ({})
    }
},

...

methods: {
    save () {
        this.$emit('reset-invoice') // where do I capture this event
    }
}

...
Answers:

If I understood your question correctly, the listening component would be the <router-view>, so:

<router-view @reset-invoice="resetInvoice"></router-view>

And in whichever component this router view is rendered:

{
  methods: {
    resetInvoice() {
      // ...
    }
  }
}

###

You should watch the route and set the props passed from the route, like below

watch: {
    '$route' (to, from) {
          this.user_id = this.$route.params.id
    },     
}