Favourite feature in Vue.js
I'm working on a vue.js/laravel favourties feature.
My last bit of code is using computed to search the users array to see if they have already favourited that item. However, I'm struggling to target the listings_id object in the favourites array.
Any ideas on the below?
return this.favourites.indexOf(this.listings_id) > -1;
Hi @Admin!
Thanks for the response. I've been playing around with the code some more trying to get my head around it. Appreciate any guidance.
Bascially I've got the class toggle working on the first button example, the computed property working on page render and (when I uncomment the code below for the favToggle(fav) ) posting and deleting to the database. I'm now looking to consolidate everything as well as my understanding :)
new Vue({
el: '#app'
});
<p>Vue.component('favourite-button', {
props: [
'id',
],</p>
<p>template:
` <input class="hidden" type="input" name="_method" value="{{ id }}" v-model="form.listings_id"></input>
<button :class="[ fav.fav ? 'favourited' : 'not-favourited' ]" @click="favToggle(fav)">{{ fav.fav }}<i class="fa fa-heart"></i></button>
<button :class="[ isFavourite ? 'favourited' : 'not-favourited' ]" @click="favToggle(isFavourite)">{{ isFavourite }}<i class="fa fa-heart"></i></button>
<pre>{{ isFavourite }}</pre></p>
<pre><code> `,
data: function() { return { form: new SparkForm({ listings_id: '' }), favourites: [], fav: { fav: false },
};
},
created() { this.getFavourites();
},
computed: {
// isFavourite: function() {
//
// for (var i = 0; this.favourites.length; i++)
// {
// if (this.favourites[i].listings_id == this.id) {
// return true;
//
// }
// }
// }
isFavourite: function(){
return this.favourites.some(function(favourite){
return favourite.listings_id === this.id
}.bind(this))
}
},
methods: {
favToggle: function(fav) {
fav.fav = ! fav.fav;
},
// favToggle(fav) {
// if (this.isFavourite) {
// this.$http.delete('/api/favourite/' + this.id);
// this.form.id = '';
//
// } else {
// Spark.post('/api/favourite', this.form)
// .then(favourite => {
// this.favourites.push(favourite);
// this.form.id = '';
//
// });
// }
// },
getFavourites() {
this.$http.get('/api/favourites')
.then(response => {
this.favourites = response.data;
});
},
}
});
Vue.component('listings', { template: '#listing-template',
data: function() {
return {
listings: [],
favourites: [],
};
},
created() {
this.getListings();
},
methods: {
getListings() {
this.$http.get('/api/listings')
.then(response => {
this.listings = response.data;
});
},
}
});