passing data from child to parent component in Vue

Viewed 3201

I am practicing Vue JS and would like to understand how to pass data from a child component to a parent component emitting an event. This is my parent component 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>

Here's the code of my BookForm component from which I would enter the book data and update the BookList emitting the 'book-is-created' and the book object:

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

When try to console log the book object it returns 'undefined'. How can I make available the book object in the BookList component in order to update my list?

1 Answers
Related