Vue 如何从子组件获取值 [英] Vue how to get value from sub component
问题描述
这是我的用例:
我的主页有几个从用户收集不同输入的子组件,最后我想提交整个页面并收集所有输入.因此我想从子组件中检索数据
My main page have several sub-components that collect different input from user, finally I want to submit the whole page with all inputs collected. Therefore I want to retrieve the data from sub-component
一种选择是使用store
,但是我的子组件超级简单,只是一些表格,store
似乎太重了...另一种选择是我可以修改prop
,虽然我知道这是不好的做法,但这种方法看起来很完美......
One option is to use store
, but my sub-components are super simple, just some forms, store
seems too heavy...
Another option is that I can modify prop
, although I know this is bad practice, but this approach looks just perfect....
如果我的逻辑很简单,可以修改prop
吗?(只收集用户的输入)或者我必须去Vuex
和store代码>
Is it ok to modify prop
if my logic is simple?(just collect inputs from user)Or I have to go for Vuex
and store
推荐答案
扩展来自 Ifaruki 和 Andres Foronda 的优秀答案,另一个相关选项是在子组件的 prop 上使用 sync
修饰符.
Expanding on excellent answers from Ifaruki and Andres Foronda, another, related option is the use of the sync
modifier on the child component's prop.
假设子组件有一个名为 name
的 prop.在父组件中,您可以像这样使用 sync
修饰符:
Suppose the child component has a prop named name
. In the parent component, you can use the sync
modifier like this:
<Child :name.sync="childName"></Child>
然后,在子组件中,当name
prop 的值应该更新时,不要直接更新它.相反,发出一个遵循可同步道具的命名约定的事件,即 update:nameOfProp
.所以在我们的例子中,子组件会这样做:
Then, in the child component, when the value of the name
prop should be updated, don't update it directly. Instead, emit an event that follows the naming convention for sync-able props, which is update:nameOfProp
. So in our example, the child component would do this:
this.$emit('update:name', newName);
同步修饰符的好处是我们不必在父组件中编写事件处理函数——Vue 会为我们完成这些并自动更新绑定到 prop 的变量.
The benefit of the sync modifier is that we don't have to write an event handler function in the parent component--Vue does that for us and updates the variable that is bound to the prop automatically.
您可以阅读有关 sync
修饰符的更多详细信息 在官方文档中.
You can read more details about the sync
modifier in the official docs.
这篇关于Vue 如何从子组件获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!