[英]How can i pass data from parent component to a child component in Vue.js?
[英]Vue.js how to pass array from child component to parent component?
我正在构建一个通讯录应用程序,并且我在子组件中创建了模态,输入字段很少。 我正在尝试使用该值并将它们添加到父组件。 我已经使用 $emit 传递了数据,但无法弄清楚如何在父组件中使用它 - 将其添加到该表行中。
这是子组件代码:
<form @submit.prevent="addContact">
<div class="form-group">
<label for="exampleInputName1">First Name</label>
<input type="text" v-model="contacts.fname" class="form-control" id="exampleInputName1"
placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="exampleInputLastName1">Last Name</label>
<input type="text" v-model="contacts.lname" class="form-control" id="exampleInputLastName1"
placeholder="Enter Last Name"
required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="email" v-model="contacts.email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter email" required>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
else.</small>
</div>
<div class="form-group">
<label for="exampleInputAdress1">Adress</label>
<input type="text" v-model="contacts.adress" class="form-control" id="exampleInputAdress1" placeholder="Enter Adress" required>
</div>
<div class="form-group">
<label for="exampleInputPhone1">Phone Number</label>
<input type="number" v-model="contacts.phone" class="form-control" id="exampleInputPhone1" placeholder="Enter Phone Number"
required>
</div>
<div class="form-group">
<label for="exampleInputCompany1">Company</label>
<input type="text" v-model="contacts.company" class="form-control" id="exampleInputCompany1" placeholder="Enter Company" required>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" @submit="addContact">Save</button>
</div>
<script>
export default {
data() {
return {
contacts: [{
fname: '',
lname: '',
email: '',
adress: '',
phone: '',
company: ''
}]
}
},
methods: {
addContact() {
this.$emit('passArr', this.contacts);
}
},
}
</script>
这是父组件:
<tbody>
<tr class="d-flex">
<td class="user col-3"></td>
<td class="col-3"></td>
<td class="col-2">}</td>
<td class="col-2"></td>
<td class="col-2"></td>
</tr>
</tbody>
<script>
import modal from './AddContactModal.vue'
export default {
data() {
return {
}
},
components: {
modal
},
methods: {
}
}
</script>
您可以像这样在父组件中侦听passArr
事件:
<parent-comp @passarr="myMethod" />
...
methods: {
myMethod(arg)
{
console.log(arg)
//arg will contain what you passed in the child method when you
// emit the event with `this.contacts` as arguments
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.