在 Vue 中将数据从子组件传递到父组件

passing data from child to parent component in Vue

提问人:Sandro Palmieri 提问时间:5/21/2017 更新时间:5/22/2017 访问量:3334

问:

我正在练习 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 组件的代码,我将从中输入书籍数据并更新 BookList,发出“book-is-created”和 book 对象:

<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>

当尝试控制台记录 book 对象时,它返回“undefined”。如何在 BookList 组件中提供 book 对象以更新我的列表?

vuejs2 vue-component

评论


答:

4赞 Bert 5/21/2017 #1

代码将 book 作为事件的参数传递,但处理程序不接受该参数。您需要做的就是将参数添加到处理程序中,您将能够在方法中使用它。book-is-createdbook

methods:{
  onClickForm(book){
    console.log(book)
    console.log('Book created')
    // this.books.push(book)
  }
}

顺便说一句,避免使用箭头函数进行定义。您当前的代码是可以的,但是如果您曾经尝试在数据函数中使用,则会引用错误的内容。只需使用典型函数或新方法语法即可。datathisthis

data(){
   return {
      book:{
        author:"",
        title:"",
        publishing_house: "",
        edition_date: ""
      }
   }
}