首页 > 解决方案 > Vuejs 路由器监听事件

问题描述

我有一个组件,其中道具通过路线传递(https://router.vuejs.org/guide/essentials/passing-props.html)。我的问题是如何监听组件发出的事件,以便改变从路由传递的道具?

在我的路线中,我有类似的东西

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

在组件内部我有一个道具

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

...

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

...

标签: vue.jsvuejs2vue-router

解决方案


如果我正确理解了您的问题,听力部分将是<router-view>,所以:

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

无论在哪个组件中呈现此路由器视图:

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

推荐阅读