Utilizing Vue.JS to fetch and showcase data retrieved from an external API

 html>
    <head>
    <title>Unique Vue App</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.7/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
 </head>

<body>
<!--
<h1>
    <a href="http://localhost:1337/"> Home Page</a>
</h1>
<h1>
    <a href="http://localhost:1337/form"> Form Page</a>
</h1>
 -->

<div id="my_view">
    <p>{{ responseOptions| json }}</p>
    <br />
    <p>{{ origin | json }}</p>
</div>

<script>
    new Vue({
        el: '#my_view',
        data: {
            origin: ''

        },
        //it is showing an empty array. It's not returning any data.
        //leave name:"name" out  and it returns the whole object?
        // example from https://github.com/pagekit/vue-   resource/blob/master/docs/http.md


 ready: function () {
            var resource =   this.$resource('https://jsonplaceholder.typicode.com/users');
            resource.get({name: "name"}).then((response) => {

                this.$set('responseOptions', response.status)
                this.$set('origin', response)
            });
        }
    })

        </script>
   </body>
   </html>

Hello, Trying to figure out how the vue-resource $http access to an api works. So created this basic page and when I load it to the browser, all I get is an empty array. I followed the instruction posted on the official page (https://github.com/pagekit/vue-resource/blob/master/docs/http.md)

I'm able to display the response.status on the page so the script is communicating but the data is not displayed at all. If you visit the page (https://jsonplaceholder.typicode.com/users) data is there.

What am I doing wrong? Please advise...

Answer №1

Take a look at this example

Upon reviewing your code, I noticed that you are using two different versions of the Vue framework simultaneously, which is not recommended. In my revised example, I have utilized Vue 2 for consistency.

Additionally, the usage of this.$resource seemed unfamiliar to me. I suggest either using Vue.http globally or this.$http within the Vue instance for clearer functionality.

In my updated version, I defined an array to store data and created a method to make an HTTP request to retrieve JSON data from the server. This data is then stored in the 'items' array within our data model.

However, it is crucial to ensure that the method is triggered. To achieve this, I recommend calling it immediately after the Vue instance is created using the created() lifecycle hook.

Finally, in the template, a simple iteration using v-for is employed to demonstrate the successful functioning of the code.

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 there a more efficient method for managing Express rendering based on whether the request is an AJAX post or an HTML form submission?

Currently, I am working on an HTML form and incorporating jQuery's AJAX post feature to retrieve information based on the success or failure of a database insertion. Within my code, I have set the ajax post variable to true when utilizing AJAX postin ...

Upon attempting to start the server, the module 'express-stormpath' could not be located

Upon trying to execute node server.js (in a regular terminal without superuser or root permissions), the following error is thrown: alphaunlimitedg@AUNs-PC:~/my-webapp$ node server.js module.js:442 throw err; ^ Error: Cannot find module 'expr ...

What is the best way to design a timetable schema in MongoDB specifically for a Teacher Schema?

Greetings to all in the StackOverflow community! I am here seeking some innovative ideas for a project I am currently working on. One of the challenges I'm facing involves storing available days within a Teacher Schema. In this application, a Teacher ...

Using AngularJS to categorize dates from JSON data into monthly groups and present them in visual charts

Trying to display JSON data in a chart using Chart.js and AngularJS based on months, but facing an issue with the date format being '2017-06-12T12:00:00.000Z'. Specifically, I am unsure how to group the data by month names (June, July, August, et ...

How can I trigger a PHP function by clicking a button on a PHP page that has already been loaded?

While I've come across a variety of examples, I haven't been able to make them work for the simple task I need to accomplish. The code in these examples seems overly complex compared to what I require. In essence, I have a form that processes dat ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

Organize 15 employees into 3 separate groups

I need to organize 9 users into teams for a training session, with each team consisting of a maximum of 3 users. Additionally, I want every user to pair up with each other by the end of the training. Currently, I am utilizing expressjs var express = requ ...

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

Update the redux state according to the value of the onChange event

I am currently working with redux and have a state that contains empty string values. I need to fill in each empty key using the onChange event from an input field. For example, if I want to update the 'business_selected' key, what should the fun ...

The slidespercolumns feature seems to be malfunctioning within the swiper slider

I am attempting to display columns based on a slider using swiper version 6.5.8. This is the HTML code: <!-- Swiper --> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swip ...

Preloading videos for optimal performance on mobile devices

Looking for a solution where 4 MP4/video files, each 5MB in size, can be played consecutively without gaps between them on all browsers and devices. Preferably not looking for a solution involving the replacement of video source files. The current approac ...

Error: Issue with parsing integer in JavaScript

I'm in the process of developing a dice game that involves rolling two dice and determining the sum. The goal is to display the running total next to the dice. However, I'm encountering an issue where NaN (Not a Number) is being displayed. Here i ...

Steps for creating a basic table filter using jQuery

What is an efficient way to create a basic table filter using jQuery without pagination requirements? I want to retrieve data from a database and display it as a list. I would like to avoid using plugins and instead opt for concise code snippets. For ...

Escaping multiple levels of quotations in a string within HTML documents

Currently, I am developing an application with Java as the backend and AngularJS 1.0 for the frontend. To display data tables, I am utilizing the veasy AngularJS plugin which I have customized extensively for my app. However, I am facing a small issue. I ...

JavaScript - Retrieve all properties and methods of an object

Can an object created through a constructor function have its keys listed using the Object.keys() method? Let's consider an example with the following code: function Foo () {} Foo.prototype.bar = 'bar'; Foo.prototype.baz = 'baz'; ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Issues with Bootstrap Contact Form submission

I found a helpful tutorial for creating a form at the following link: After following the tutorial, I added these scripts to the bottom of my contact form HTML: <script src='https://code.jquery.com/jquery-1.12.0.min.js'></script> ...

Is it possible to effortlessly update all fields in a mongoose document automatically?

Take for instance the scenario where I need to update a mongoose document in a put request. The code template typically looks like this: app.put('/update', async(req,res) => { try{ const product = await Product.findById(req.body.id) ...