我有一个非常小的应用程序,有一个捐赠表格.表单引导用户完成填写信息的步骤.我有一个主要组件,它是表单包装器和主Vue实例,它包含所有表单数据(模型).所有子组件都是捐赠过程中的步骤.每个子组件都有要填写的输入字段,这些字段将更新父模型,以便在提交表单时我拥有父模型中的所有表单数据.以下是组件的组合方式:
<donation-form></donation-form> // Main/Parent component
Run Code Online (Sandbox Code Playgroud)
donation-form组件内部 :
<template>
<form action="/" id="give">
<div id="inner-form-wrapper" :class="sliderClass">
<step1></step1>
<step2></step2>
<step3></step3>
</div>
<nav-buttons></nav-buttons>
</form>
</template>
Run Code Online (Sandbox Code Playgroud)
现在,我正在设置每个子组件中输入的数据,然后我有一个watch方法正在监视要更新的字段,然后我$root通过执行此操作将它们推送到...
watch: {
amount() {
this.$root.donation.amount = this.amount;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我的一个步骤我有很多字段,而且我似乎在编写一些重复的代码.此外,我确信这不是最好的方法.
我尝试将数据作为一个传递prop给我的子组件,但似乎我无法更改子组件中的道具.
除了将监视添加到子组件中的每个值之外,更新根实例甚至父实例的更好方法是什么?
更多示例
这是我的step2.vue文件 - step2 vue文件
这是我的donation-form.vue文件 - 捐赠形式的vue文件
Cod*_*Cat 24
您可以使用自定义事件将数据发回.
要使用自定义事件,您的数据应该在父组件中,并作为props传递给子项:
<step1 :someValue="value" />
Run Code Online (Sandbox Code Playgroud)
现在您想要从子级接收更新的数据,因此向其中添加一个事件:
<step1 :someValue="value" @update="onStep1Update" />
Run Code Online (Sandbox Code Playgroud)
您的子组件将发出事件并将数据作为参数传递:
this.$emit('update', newData)
Run Code Online (Sandbox Code Playgroud)
父组件:
methods: {
onStep1Update (newData) {
this.value = newData
}
}
Run Code Online (Sandbox Code Playgroud)
以下是自定义事件的简单示例:http:
//codepen.io/CodinCat/pen/QdKKBa?edit = 1010
如果所有step1,step2和step3都包含大量字段和数据,则可以将这些数据封装在子组件中(如果父组件不关心这些行数据).
所以每个孩子都有自己的数据并与之绑定 <input />
<input v-model="data1" />
<input v-model="data2" />
Run Code Online (Sandbox Code Playgroud)
但同样,您将通过事件发回结果数据.
const result = this.data1 * 10 + this.data2 * 5
this.$emit('update', result)
Run Code Online (Sandbox Code Playgroud)
(再次,如果您的应用程序变得越来越复杂,vuex将成为解决方案.
我个人更喜欢在使用表单时使用通用函数来更新父表,而不是为每个孩子编写一个方法.为了说明 - 有点浓缩 - 在父母中这样:
<template lang="pug">
child-component(:field="form.name" fieldname="name" @update="sync")
</template>
<script>
export default {
methods: {
sync: function(args) {
this.form[args.field] = args.value
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
在子组件中:
<template lang="pug">
input(@input="refresh($event.target.value)")
</template>
<script>
export default {
props: ['field', 'fieldname'],
methods: {
refresh: function(value) {
this.$emit('update', {'value': value, 'field': this.fieldname});
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)