vue,发射与传递函数作为道具 [英] vue, emitting vs passing function as props

查看:29
本文介绍了vue,发射与传递函数作为道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个在其他几个组件中导入的按钮组件.我希望子组件不与单击按钮时发生的任何一种类型的逻辑耦合.所以我想在利用此按钮组件的各种组件中保留该逻辑.

Let's say I have a button component that is imported in several other components. I want the child component to not be coupled to any one type of logic that happens when the button is clicked. So I want to hold that logic in the various components that leverage this button component.

我认为至少有两种方法可以解决这个问题.

I think there are at least 2 ways of going about this.

  1. 让孩子向父母发出一个事件,然后让父母定义处理程序.

  1. Have the child emit an event to the parents, and then let the parents define the handler.

定义父级中的处理程序并将其作为道具传递给按钮组件.

Define the handlers in the parents and pass it down as props to the button component.

我习惯于在 React 中做后者.在 vue 中是否有针对这种情况的最佳实践?

I'm used to doing the latter in React. Is there a best practice in vue for this situation?

推荐答案

Vue 的哲学是道具向下,事件向上.第一个选项紧随其后,因为事件本身被(向上)发送到父级,然后被处理.

The Vue philosophy is props down, events up. The first option follows that closer as the event itself is emitted (up) to the parent and then handled.

同样在 Vue SFC 中,你还有一个额外的好处,就是在绑定属性前面加上 v-on(或@),它将其意图描述为一个向上移动的事件,而不是 v-bind(或 :),这意味着它是一个prop 即使它实际上是对事件的回调.

Also within a Vue SFC you have the added benefit of prefixing the bound attribute with a v-on (or @) which describes its intent as an event traveling up and not a v-bind (or :) which implies it's a prop even though its really a callback to an event.

这篇关于vue,发射与传递函数作为道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆