视图 | 如何将所有内容发送给父级

Net*_*ali 1 vue.js vuejs2 vuejs3

Vue 有没有办法将所有发射器发送给父级监听?

例如转动该代码:

<DetailsPages
  v-if="$route.hash === '#details_pages'"
  v-on:next="$emit('next')"
  v-on:need-to-save="save => $emit('need-to-save', save)"
  v-on:goto-step="step => $emit('goto-step', step)"
/>
<DetailsContact
  v-if="$route.hash === '#details_contact'"
  v-on:next="$emit('next')"
  v-on:need-to-save="save => $emit('need-to-save', save)"
  v-on:goto-step="step => $emit('goto-step', step)"
/>
<DetailsInfo
  v-if="$route.hash === '#details_info'"
  v-on:next="$emit('next')"
  v-on:need-to-save="save => $emit('need-to-save', save)"
  v-on:goto-step="step => $emit('goto-step', step)"
/>
Run Code Online (Sandbox Code Playgroud)

像这样的事情:

<DetailsPages v-if="$route.hash === '#details_pages'" v-on:emit="$emit" />
<DetailsContact v-if="$route.hash === '#details_contact'" v-on:emit="$emit" />
<DetailsInfo v-if="$route.hash === '#details_info'" v-on:emit="$emit" />
Run Code Online (Sandbox Code Playgroud)

Rom*_*lex 6

在 Vue 2 中,您可以将所有父侦听器应用到子组件,如下所示:

<DetailsPages v-on="$listeners" />
Run Code Online (Sandbox Code Playgroud)

Vue 3通过将 $listeners 合并到 $attrs 中来删除它们。你仍然可以像这样实现你想要的:

<DetailsPages v-bind="$attrs" />
Run Code Online (Sandbox Code Playgroud)

但是,请考虑到虽然 $attrs 包含 $listeners,但它还包含其他内容