Vue | 如何将所有内容传递给父组件

huangapple go评论59阅读模式
英文:

Vue | How to emit all to parent

问题

这是一个Vue中的事件发射器修改示例:

<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" />

如果您有任何其他问题或需要进一步的帮助,请告诉我。

英文:

Is there a way in Vue to emit all emitters to parent listening?

For example turn that code:

<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)"
/>

to something like this:

<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" />

答案1

得分: 6

在Vue 2中,您可以像这样将所有父组件的监听器应用到子组件:

<DetailsPages v-on="$listeners" />

Vue 3已移除 $listeners,并将它们合并到了$attrs中。您仍然可以通过以下方式实现您想要的效果:

<DetailsPages v-bind="$attrs" />

但请注意,尽管$attrs包含了$listeners,但它还包括其他内容。

英文:

In Vue 2 you can apply all parent listeners to the child component like that:

&lt;DetailsPages v-on=&quot;$listeners&quot; /&gt;

Vue 3 removed $listeners by merging them into $attrs. You can still achieve what you want like this:

&lt;DetailsPages v-bind=&quot;$attrs&quot; /&gt;

However, take into account that while $attrs contains $listeners, it also includes other things

huangapple
  • 本文由 发表于 2023年7月12日 22:56:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定