0👍
✅
There is too much refactoring that needs to be done to code which can’t be explained here. So here is the working fiddle
I’ll just point out the key changes:
-
You are adding and subtracting votes on the component but you are getting data via props , so you should update the parent by emitting an event. Useful links: custom events, props are one-way
-
You can use a computed property to calculate total votes in the parent ass now upvotes and downvotes are making changes to main data present in parent
-
pass the total votes from parent to child component as props to calculate percentage votes
Vue.component('post', { template: "#post-template", props: ['post', 'total'], data: function () { return { upvoted: false, downvoted: false, }; }, computed:{ percentVotes(){ return (this.post.votes/this.total * 100).toFixed(2) } }, methods: { upvote: function () { if(!this.upvoted){ this.upvoted = true; this.downvoted = false; this.$emit('upvoted'); } }, downvote: function () { if(!this.downvoted){ this.downvoted = true; this.upvoted = false; this.$emit('downvoted'); } } } }); var vm = new Vue({ el: "#app", data: { posts: [{ title: "A post for our reddit demo starting at 15 votes", votes: 15 }, { title: "Try out the upvoting, it works, I promise", votes: 53 }, { title: "coligo is the bomb!", votes: 10 }] }, methods: { upvoted(post){ post.votes = post.votes +1; }, downvoted(post){ post.votes = post.votes - 1; } }, computed:{ totalVotes(){ var postVotes = this.posts.map((post) => { return post.votes; }); var getTotal = function (total, num) { return total + num; } return postVotes.reduce(getTotal); } } });
Source:stackexchange.com