我正在练习Vue JS,并且想要了解如何将数据从子组件传递到发出事件的父组件。 这是我的父组件BookList:
<template>
<div class="booklist">
<BookForm @book-is-created="onClickForm" />
<table v-for="book in books">
<tr>
<th> Author </th>
<th> Title </th>
<th> Publishing House </th>
<th> Edition Date </th>
</tr>
<tr>
<td> {{ book.author}}</td>
<td> {{ book.title}}</td>
<td> {{ book.publishing_house}}</td>
<td> {{ book.edition_date}}</td>
</tr>
</table>
</div>
</template>
<script>
import BookForm from './BookForm';
export default {
name: 'hello',
data: () => ({
books: []
}),
mounted() {
axios.get("http://localhost:3000/api/v1/books")
.then(response => {this.books = response.data})
},
components:{
BookForm
},
methods:{
onClickForm(){
console.log(this.book)
console.log('Book created')
}
}
}
</script>
这是我的BookForm组件的代码,我将从中输入书籍数据并更新发布“book-is-created”和书籍对象的BookList:
<template lang="html">
<form>
<label for="author">Author</label>
<input v-model="book.author"type="text" name="author" value="">
<br>
<label for="title">Title</label>
<input v-model="book.title" type="text" name="title" value="">
<br>
<label for="publishing_house">Publishing house</label>
<input v-model="book.publishing_house" type="text" name="publishing_house" value="">
<br>
<label for="edition_date">Edition Date</label>
<input v-model="book.edition_date" type="text" name="edition_date" value="">
<br>
<button v-on:click.prevent="createBook" >createBook</button>
</form>
</template>
<script>
export default {
data:() =>({
book:{
author:"",
title:"",
publishing_house: "",
edition_date: ""
}
}),
methods:{
createBook: function() {
//console.log(this.book)
this.$emit('book-is-created', this.book)
}
}
}
</script>
当尝试控制日志书对象时,它返回'undefined'。如何在BookList组件中提供book对象以更新列表?
答案 0 :(得分:2)
代码将book作为book-is-created
事件的参数传递,但您的处理程序不接受该参数。您需要做的就是将book
作为参数添加到您的处理程序中,您就可以在方法中使用它。
methods:{
onClickForm(book){
console.log(book)
console.log('Book created')
// this.books.push(book)
}
}
作为旁注,请避免使用箭头功能定义data
。您当前的代码没问题,但如果您曾尝试在数据函数中使用this
,this
会引用错误的内容。只需使用典型函数或新方法语法。
data(){
return {
book:{
author:"",
title:"",
publishing_house: "",
edition_date: ""
}
}
}