Favourite feature in Vue.js
Vue.component('favourite-button', { props: [ 'id', ],
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>
`,
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;
});
},
}
});</code></pre>

