Implementing a method to display specific user posts using Vue.js AJAX API integration

How can I display 5 user posts in a modal using HTML and JavaScript?

HTML:

<div id="app">
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user,i in users">
          <td><b-button v-b-modal.modal-1 v-on:click="Showpost(user.id, i)">{{user.id}}</b-button></td>
          <b-modal id="modal-1" title="info">
            <p class="my-4">{{posts.title}}</p>
          </b-modal>
          <td>{{user.name}}</td>
        </tr>
      </tbody>
    </table>
  </div>

JavaScript:

new Vue({
  el: "#app",
  data: {
    users: [],
    posts: [],
  },
  methods: {
    Showpost(id, i) {
      console.log("id", id);
      console.log("i", i)
      fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
        .then(response => response.json())
        .then((data) => {
          this.posts = data[i];
        })
    },
  },
  computed: {
    object: function(){
      return this.posts.filter(function(post){
        return post.userId >= 5
      })
    },
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then((data) => {
        this.users = data;
      })
  },
});

Answer №1

Let me provide you with a simple code example to demonstrate how this task can be accomplished.

Firstly, consider the following code snippet:

<tbody>
    <tr v-for="(user,index) in users">
      <td> <b-button v-b-modal.modal-1 v-on:click="showUserPosts(user.id,index)">{{user.id}}</b-button></td>
      <b-modal  id="modal-1" title="info" >
      </b-modal>
      <td>{{user.name}}</td>
    </tr>
  </tbody>

Instead of changing just one element like this:

      this.posts = data[i];

Simplify your approach by doing the following:

      this.posts = data;

Also, within your HTML code, after the table tag, add the following:

<p v-for="(post,index) in posts" v-text="post.title"></>

If you only want to display a single post instead of multiple ones, modify your function like this:

data:function {
return{
users: [],
posts: {},
}
 },

And utilize the following code snippet:

<p v-if="post.title" v-text="post.title"></>

I trust that these instructions will be beneficial for you. Best of luck!

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

Display a picture within a cell of a table using Javascript

I'm currently utilizing JavaScript to generate a dynamic table that displays data parsed from a JSON object. I'd like to include an image in one of the cells directly from the JSON object using HTML code, such as: jsonObject[0].Image = <img s ...

The issue of Angular UI Bootstrap buttons not updating persists even after the removal of an

My Radio-bottoms are powered by an Array for a Multi-Choice answer setup. <div ng-repeat="option in options"> <div> <button type="button" style="min-width: 100px" class="btn btn-default" ng-model="question.answer" btn-radio="' ...

Retrieve the value of a nested JSON object using the name of an HTML form field, without the use of eval

I am facing a similar issue to Convert an HTML form field to a JSON object with inner objects, but in the opposite direction. Here is the JSON Object response received from the server: { company : "ACME, INC.", contact : { firstname : "Da ...

The ion-input border seems to be fluctuating as the keyboard appears on the screen

I'm currently working with Ionic 3 and experiencing an issue where the selected ion-input's border in the ion-content is shifting when the device keyboard appears on the screen. Here is a visual representation of the problem: https://i.stack.imgu ...

What steps can be taken to deter users from repeatedly liking comments, similar to the systems seen on Facebook or YouTube for like/dislike features?

I am currently working with express, react, and MySQL. My goal is to implement a like/dislike system for comments. After doing some research, I found that many suggest disabling the like button after a single click. However, I want users to be able to se ...

How can I retrieve the line number of a code during runtime in JavaScript?

Is there a way to add a console.log statement that would indicate the line number it is on in JavaScript? For example: console.log ('Line:', [code to get the line]). The output in the console would be Line: [line number], helping me identify wher ...

Show multiple items using v-for in a single textarea

Looking for a solution to display looped values within a single textarea instead of separate textareas. Currently using Laravel and Vue, which is showing the values individually in their own textarea elements. <textarea> <div v-for="(ite ...

When should data be processed using the API in vuex?

When working with pagination in the store, I have a small query. For example, here is the information returned from the backend: {last_page: 5, current_page: 1, per_page: 10, total: 100, count: 100, url: 'xyz.com'} The view that I need to transf ...

JQuery Mobile applies X to all divs with the specified class

I am currently working on a JQuery mobile website with an image slider on 2 different pages. In order to activate the sliders, I am using the following JavaScript code: $(function () { $("#slider").excoloSlider(); }); where '#slider' refers ...

Conceal the header and footer during the loading of particular pages

For my Angular 1.x application, I needed a way to hide the header and footer on specific pages. To achieve this, I added a 'navigateOut' data property to my state definitions. Using ng-if in my template, I was able to show/hide elements such as t ...

Uncover concealed words within PDF documents

While incorporating PDF.js to display LaTeX typeset PDF files on my website, I encountered an issue. I have concealed specific text in the PDF, but it remains searchable when viewed in Acrobat Reader. Is there a method to search for hidden text using PDF ...

ngTagsInput - Enable the onTagAdding feature

I've been attempting to establish a default function for the onTagAdding callback using the tagsInputConfig provider, but without any success. tagsInputConfig.setDefaults('tagsInput', { placeholder: 'Search', maxTags: 10, ...

Is it possible to upload the production build CSS of a Nuxt app to a Content Delivery Network

My Vue app(Nuxt) consists of multiple components with scoped CSS. Our goal is to minify all of our CSS into a single file and host it on a CDN for improved caching and reduced load on the web server. <style scoped> .a{ background-color: blue; } ...

Integrate React tags with Redux form to ensure the values are transmitted as an array within the payload

I am currently working on a redux-form that contains a component for tags. I am struggling to figure out how to retrieve the tag values in an array as a payload. Any help would be greatly appreciated. Below is the code snippet for the tags component: ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...

Saving data to MongoDB using async operations in node.js with an array

My task involves manipulating a string and extracting specific values from it. Here is an example: var my_str = "Jenny [id:51], david, Pia [id:57], Aston [id:20], Raj, "; To achieve this, I am utilizing a function called convert_to_array(my_str) which sh ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

Is there a way to maintain the current object while changing only one of its properties?

Consider the following array of objects: let data = [{ firstname: 'John', lastname: 'Doe' }, { firstname: 'Jane', lastname: '- Doe' ...