tux
tux

Reputation: 1287

Vuejs router listen to events

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
    }
}

...

Upvotes: -1

Views: 3566

Answers (3)

marvinc
marvinc

Reputation: 61

It seems I'm too late but in case someone needed it.

created() {
    // watch the params of the route to fetch the data again
    this.$watch(
      () => this.$route.params,
      () => {
        //perform here your awesome logic
      },
      // fetch the data when the view is created and the data is
      // already being observed
      { immediate: true }
    )
  },

Upvotes: 0

Yom T.
Yom T.

Reputation: 9180

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() {
      // ...
    }
  }
}

Upvotes: 4

Qonvex620
Qonvex620

Reputation: 3972

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
    },     
}

Upvotes: 0

Related Questions