Vue.js tutorial: Displaying the like count on every post

Code Snippet in My Home.vue File:

<template>
    <div>
        <my-post
            v-for="(post, index) in posts"
            :post="post"
            :index="index"
            :key="post.id"
        ></my-post>
    </div>
</template>

<script>
    import Post from './Post.vue';

    export default {
        data() {
            return {
                posts: []
            }
        },
        mounted() {
            axios.get('http://localhost/mine/test')
                .then(response => {
                    this.posts = response.data.posts;
                })
                .catch(error => {
                    // console.log(error);
                })
        },
        components: {'my-post': Post}
    }
</script>

Code Snippet in My Post.vue File:

<template>
    <div class="post">
        <!-- The content of the post...
        I want to count the number of likes for each post here something like this:
        <p>{{likes.length}}</p> -->
    </div>
</template>

<script>
    export default {
        props: ['post'],
        data() {
            return {}
        }
    }
</script>

The data retrieved by

axios.get('http://localhost/mine/test')
consists of posts and likes arrays shown below:

posts: Array [
    {0:first_name:'example123',post_id:1},
    {1:first_name:'example456',post_id:2},
    {2:first_name:'example789',post_id:3},
],
likes: Array [
    {0:first_name:'example1',post_id:1},
    {1:first_name:'example2',post_id:1},
    {2:first_name:'example3',post_id:1},
]

Note that posts and likes are separate entities. They are not related as parent-child.

Even though I passed likes as props similar to posts, it displays the same number of likes for all posts. How can I display the correct number of likes for each post?

Thank you

Answer №1

To optimize your schema, it is recommended to update it so that each post has a separate likes object defined within it.
If updating the schema is not feasible, you can make changes to your code by following these steps.

Introduce a likes field to hold all the 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}
}

Utilize filters to assign [likes] property containing specific likes for 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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95e3e0f0d5a7bba0bba4a2">[email protected]</a>/dist/vue.js" type="text/javascript"></script>

<div id="app">

</div>

Answer №2

To begin, make sure to include a "like_count" field in your database schema. Assuming you are utilizing a REST service that supports basic HTTP methods such as GET, POST, PUT, and DELETE.

Next, create a simple API call within your post component.

<template>
    <div class="post">

       <!-- Customize this section as desired -->
       <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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The method defined in user.model.js cannot be utilized in mongoose and node

When developing an app with node and mongoose, I encountered a peculiar issue while testing. Below is my auth.index.js file for user login. auth.index.js: var express = require('express'); var mongoose = require('mongoose'); var passp ...

Similar to Laravel's service providers or WordPress style plugins, Node.js has its own unique way of managing and extending functionality

Coming from a PHP/Laravel background, my team is considering using Node.js (and sails) for our upcoming project - a collaboration studio for scholars. However, before making the transition, I am curious about the best practices for creating Laravel-style s ...

Discover the process of implementing Firebase Authentication in Deno Fresh!

I've been trying to set up authentication in Fresh using the official Firebase documentation, https://firebase.google.com/docs/auth but I can't seem to get it to work. Does anyone know of any other resources like docs, articles, or blogs that co ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

liberating RAM in three.js

My application is loading a large number of meshes. When I try to dispose of old meshes to free up memory, it seems the memory is not actually being released. Am I missing something? Here is a simple example to reproduce the issue: Load 100 large binary ...

"Reasons Why I'm Unable to Retrieve the Length of an Array

Can someone lend a hand with finding the array length? I attempted to utilize Object.keys for this task { "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#sites('volagas.sharepoint.com')/sites('volagas.sharepoint.com%2C9 ...

VueJS throwing an error due to failed type check on prop

Using a component called CardRenderer.vue to render card using an array of Objects has been quite challenging for me. Repeatedly, I have used the same component to render the data and encountered this error: "[Vue warn]: Invalid prop: type check failed for ...

How to Invoke JavaScript Functions within jQuery Functions?

I'm working on a jQuery function that involves dynamically loading images and checking their width. I have two JavaScript functions, func1() and func2(), that I want to call from within the jQuery function in order to check the width of each image. T ...

when webpack loads the bundle.js file, the mime type is converted to text/html

I'm currently working on implementing server side rendering for an application using react-redux and express for the server. We are also utilizing webpack to bundle our assets. To get started, I referred to the following documentation: https://redux ...

Create an XML file with recurring elements based on JSON data

Currently, I am utilizing the xmlBuilder library within Nodejs to generate XML from a prepared JSON object. My approach involves crafting the JSON structure first and then transforming it into XML using Javascript as the coding language. The specific XML ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

Tips for adjusting the position of an object when resizing the window

The problem at hand is as follows: Upon refreshing the page, my object is initially positioned correctly. However, resizing the window causes the object to resize and reposition correctly. But, if I refresh the page after resizing the window, the object i ...

Changing innerHTML in CoffeeScript

Are there other options instead of using the 'innerHTML' property in CoffeeScript? In JavaScript, you typically write something like this: document.getElementById('element').innerHTML = "blah_blah" Is there a different approach to ac ...

Is it not possible to make updates while the state is already in transition?

this.state = { filterData: [{ attribute: '-1', filter: '-1', value: '' }], } _createFilterUI(dataSourceColumns) { if (this.state.dataSourceIndex == -1) return <div > Kindly first select Data Sourc ...

A TypeError is thrown when attempting to use window[functionName] as a function

I came across this page discussing how to call a function from a string. The page suggests using window[functionName](params) for better performance, and provides an example: var strFun = "someFunction"; var strParam = "this is the parameter"; //Creating ...

Guide on implementing the onSignInChanged event handler in a Chrome extension for Gmail

Here is a glimpse of the code from my Google Chrome extension: Manifest: "content_scripts": [ { "matches": [ "https://mail.google.com/*", "https://inbox.google.com/*" ], "js": ["js/jquery-3.2.1.min.js", "js/content.js"], "css": ["css/custom ...

Populate Dropdown menu using JSON data

-- Controller -- [WebMethod] public ActionResult GetSellers() { List<Seller> sellers = db.Sellers.ToList(); return Json(sellers, JsonRequestBehavior.AllowGet); } -- View -- @Html.DropDownListFor(x => x.SellerId, new SelectList(Enumerab ...

The ng-include directive is having trouble finding the partial HTML files

I've been working on setting up a basic tabset with each tab pulling content from a separate partial view with its own controller. To test everything out, I created three dummy HTML files with simple text only. However, I'm having trouble getting ...

Dividing component files using TypeScript

Our team has embarked on a new project using Vue 3 for the front end. We have opted to incorporate TypeScript and are interested in implementing a file-separation approach. While researching, we came across this article in the documentation which provides ...

What is the process for translating HTML elements into JSX format?

I have a couple of inquiries. 1.) I am working on a basic reactjs component. How can I transform it into JSX? I want the code to follow the reactjs style. 2.) If I receive an array from the backend in this format [ '/parent-folder-1/child-folder ...