0👍
✅
Ideally you need to update your schema, such that each post have a likes object defining them separately.
Incase its not possible you can modify your code by doing this.
Add a likes
field having all likes.
export default {
data() {
return {
posts: [],
likes:0
}
},
mounted() {
axios.get('http://localhost/mine/test')
.then(response => {
this.posts = response.data.posts;
this.likes = response.data.likes;
})
.catch(error => {
// console.log(error);
})
},
components: {'my-post': Post}
}
Use filter to add/pass [likes
] prop with likes specific to each post.
<my-post
v-for="(post, index) in posts"
:post="post"
:likes="likes.filter(x => x.post_id==post.post_id)"
:index="index"
:key="post.id">
</my-post>
CODE SNIPPET
function callMe() {
var post = Vue.component("post", {
template: "<p>PostId={{post.post_id}} . Number of likes: {{likes.length}}</p>",
props: {
likes: Array,
post: Object
},
data() {
return{
numberOfLikes:0
}
},
methods: {
}
})
var vm = new Vue({
el: '#app',
template: '<p><post v-for="(postObj,index) in post.posts" :post="postObj" :likes="post.likes.filter(x => x.post_id==postObj.post_id)"></post></p>',
data(){
return {
likes:0,
post:{
posts: [
{first_name:'example123',post_id:1},
{first_name:'example456',post_id:2},
{first_name:'example789',post_id:3},
],
likes: [
{first_name:'example1',post_id:1},
{first_name:'example2',post_id:1},
{first_name:'example3',post_id:1},
{first_name:'example4',post_id:2},
]
}
}
}
})
}
callMe();
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js" type="text/javascript"></script>
<div id="app">
</div>
0👍
First you should add a “like_count” (or whatever you wish) to your db scheema. I assume you are using some kinda REST service that supports basic http methods ie GET,POST,PUT,DELETE.
Then just do a simple api call in your post component.
<template>
<div class="post">
<!-- Whatever you wish to stylize -->
<button class="add-like" @click="addLike"> +1 </button>
<p>{{currentLikes}}</p>
</div>
</template>
<script>
export default {
props: ['post'],
computed: {
currentLikes () {
return parseInt(this.post.like_count) + 1
}
},
methods: {
addLike () {
axios.put('/yourlink/' + this.post.post_id, {
like_count: this.currentLikes
})
}
}
}
</script>
Source:stackexchange.com