Jun 6, 2017
0
Level 2
Passing an array of selected checkboxes back to parent
Hi guys,
How do I pass an array of selected checkbox from child to parent? I have the code shown below, my events are working as expected except that the final selected books is showing the same array of values when I uncheck it.
// Code
let bookList= Vue.component('bookList', {
data: function () {
return {
selectedBooks: []
}
},
props: {
user_book: Object
},
template: '#book-template',
methods: {
updatedSelectedBooks: function(event) {
console.log(event.target.value);
this.selectedBooks.push(event.target.value);
this.$emit('book-selected', this.selectedBooks);
}
}
});
let bookListComponent = Vue.component('book-list', {
template: '#book-list',
data: function () {
return {
isLoading: false,
selectedBooks: [],
books: [
{id: 1, name: 'Book 1'},
{id: 2, name: 'Book 2'},
{id: 3, name: 'Book 3'},
{id: 4, name: 'Book 4'}
]
}
},
components: {
bookList
},
methods: {
loadBooks: function () {
let self = this;
self.isLoading = true;
axios.get(laroute.route('get.books'))
.then(function (response) {
self.isLoading = false;
self.books= response.data.books;
console.log(response);
})
.catch(function (error) {
self.isLoading = false;
})
}
},
mounted: function () {
this.loadBooks();
},
computed: {
bookNotSelected: function() {
return typeof this.selectedBooks !== 'undefined';
},
noBooks: function () {
return this.books.length !== 0;
}
}
});
// Templates
<template id="book-list">
<div>
<h4 v-show="isLoading" class="text-center">
<i class="fa fa-circle-o-notch fa-spin fa-2x"></i><br />
...Loading your books...
</h4>
<div v-if="!isLoading && !noBooks" class="text-center">
<h4>You have no books</h4>
</div>
<div v-if="!isLoading">
<ul class="nav nav-stacked">
<book-list v-for="(book, index) in books" v-bind:key="book.bookId" v-bind:user_book="user_book" v-bind:selectedBooks="selectedBooks" @book-selected="selectedBooks = $event"></book-list>
</ul>
<div class="row">
<div class="col-md-6">
<router-link to="/" class="btn btn-default btn-block">< Back</router-link>
</div>
<div class="col-md-6">
<router-link to="/" class="btn btn-primary btn-block" v-bind:disabled="!bookNotSelected">Request Books</router-link>
</div>
</div>
</div>
</div>
</template>
<script type="text/x-template" id="book-template">
<div>
<li class="margin-bottom active">
<a href="javascript:void(0)"
class="box-title">
<div class="row">
<div class="col-md-12">
<div class="pull-left text-left">
<input type="checkbox" name="book[]" v-bind:value="books.bookId" v-on:change="updatedSelectedBooks"> <strong>@{{ book.name }}</strong>
</div>
</div>
</div>
</a>
</li>
</div>
</script>
Is there a way I can resolve this problem and ensure that when I check / uncheck an item, the correct values are reflected the in selectedBooks array...
Thanks
Please or to participate in this conversation.