Determining the position of a v-for element in Vue.js when making an HTTP request

I'm faced with a challenge involving an array of posts with comments, each post having an input for creating a new comment. The posts array contains the id of each post as a prop, but I'm unsure how to select the specific post for which I want to create a comment. I need this specific post id to link the comment to the correct post in my database, but I'm struggling to figure out how to identify that id.

These are examples of the structure:

{"userId": 1, "id": 3, "title": "ea molestias", "body": "et iusto sed quo" }

    <v-row class="mb-6" justify="center">
  <v-col
    xs="12"
    sm="12"
    md="10"
    lg="8"
    v-for="post in posts"
    v-bind:key="post.id"
  >
    <v-card dark>
      <v-card-title class="c-t">Title: {{ post.title }}</v-card-title>
      <v-card-subtitle class="text-left c-t"
        >User: {{ post.id }}</v-card-subtitle
      >
      <v-card-text class="text-left"
        >Description: {{ post.description }}</v-card-text
      >

      <v-card-actions>
        <v-btn text color="warning accent-4">
          Edit
        </v-btn>

        <v-btn text color="red accent-4">
          Delete
        </v-btn>
      </v-card-actions>

      <v-card-text>
        <v-divider class="mx-4"></v-divider>
        <v-card-subtitle class="text-left com-t">Comments</v-card-subtitle>

        <!-- Comments loop -->
        <div class="conditional" v-if="post.comments != null">
          <v-card
            class="mb-2"
            v-for="comment in post.comments"
            v-bind:key="comment.id"
          >
            <v-card-title class="text-left comment"
              >User {{ comment.name }}</v-card-title
            >
            <v-card-subtitle class="text-left comment">{{
              comment.email
            }}</v-card-subtitle>

            <v-card-text class="text-left comment">{{
              comment.body
            }}</v-card-text>
          </v-card>
        </div>
      </v-card-text>

      <!-- Search  -->
      <v-form ref="form" lazy-validation>
        <v-row class="mb-6" justify="center" align="center">
          <v-col xs="6" sm="8" md="8" lg="8">
            <v-text-field
              v-model="comment"
              label="Comment"
              class="ml-2"
            ></v-text-field>
          </v-col>

          <v-col xs="2" sm="2" md="2" lg="2">
            <v-btn color="success" @click="createComment">Send</v-btn>
          </v-col>
        </v-row>
      </v-form>
    </v-card>
  </v-col>
</v-row>

In my scripting section, I'm using v-model to capture the comment and emit an event to pass it to the parent component for the post http request. However, I'm stuck on how to retrieve the current post's id when the "Create comment" button is clicked.

Feel free to check out my code on Github: https://github.com/roninMo/vueRestfulApi/blob/master/src/components/Posts.vue

Answer №1

                <v-btn color="success" @click="createComment(post.id)">Send</v-btn>

By triggering the click function, the id is captured and sent along with the request. Apologies for any inconvenience caused, and appreciation for your generosity!

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

Is it possible to modify state prior to the link being activated in react-router-dom?

I need to gather user information before the link works, but I'm not sure how to do that. The issue is that when I click on the link, the component it's linking to gets activated first without receiving the necessary info. const [userId, setUse ...

Prevent multiple requests on jQuery infinite scrolling

I have implemented pagination on my website where the next page is loaded automatically when the user reaches the bottom of the page. This is achieved by using jQuery's .on('scroll', this.detectScroll()) method which triggers a function to l ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

displaying several gltf 3D models simultaneously on a map using mapbox gl and three js

Recently, I encountered an issue with adding glTF 3D models to a map using Mapbox GL and Three.js. It seems that while I can successfully add a single glTF model in a separate layer on the map, I am facing difficulties when trying to add multiple glTF mode ...

Is there a way to arrange list items to resemble a stack?

Typically, when floating HTML elements they flow from left to right and wrap to the next line if the container width is exceeded. I'm wondering if there's a way to make them float at the bottom instead. This means the elements would stack upward ...

How can I change :hover to a clickable element instead?

I attempted to create a full-width accordion with the following code: .page { margin: 0; padding: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; height: 100vh; } .content { -webkit- ...

`Thoughts on Difficulty Attaching Child Elements in JavaScript with appendChild`

I am having trouble with appending some HTML that is being received as a string in a div. For some reason, the appendChild method is not working as expected. Here is my JavaScript code: var doc = document.getElementById("products"); var notes = doc.getEle ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Understanding the fundamental concepts of callbacks with Backbone.js

Currently, I am working with Backbone to send a login form to my server. Once the form is submitted and the database query is successful, a boolean value is flipped to enable GET responses from the server. However, the issue arises when it attempts to fetc ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Populating and dynamically sorting a v-select component in Vuetify

I am working on populating and sorting an array dynamically for use in a v-select component. However, I am encountering the es-lint warning 'unexpected side-effect in computed property' because I am modifying objects within that function call. Is ...

The error ElementNotVisibleError occurs in Selenium::WebDriver when attempting to use the send_key function with a Chrome browser, as the element is not currently visible

A problem has arisen with the Ruby Selenium script I am running in parallel. The issue occurs when attempting to send text input through send_key on a webpage while using the Chrome browser. Selenium::WebDriver::Error::ElementNotVisibleError: element not ...

Ways to identify whether the ajax error is due to Access-Control-Allow-Origin restriction or if the file is genuinely absent

My question pertains to customizing error messages for Access-Control-Allow-Origin issues and outdated URLs. I want to display specific messages to the user based on different types of errors that may occur. Currently, my code looks like this: $.ajax( { ...

`replaceWith function limited to single use`

I'm encountering an issue where the replaceWith function is only working on the first instance. Even though I am getting updated data, it's not being written to the div after the initial replacement. $( "#searchboxform" ).keyup(function() { ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

Instructions for converting a blob URL into an audio file and securely storing it on the server

After successfully recording and adding the audio to my HTML page within the audio tag, I managed to obtain the blob source URL from the tag using the following line: var source = document.getElementById("Audio").src; The blob source URL looks ...

Ways to modify the hue of an li element in the context menu upon hovering

I'm currently working on a project that involves VueJS and Bootstrap. To enhance user experience, I've incorporated a context menu using the npm package called vue-context Vue Context Menu When a user hovers over an item on the context menu, the ...