Struggling to integrate data retrieved from a Vue.js API

Once I receive the API call with an attached string input, I successfully get the result. However, I am struggling to incorporate it into my frontend. I have attempted various solutions found online without success and cannot seem to grasp the concept. Here's what I have tried so far:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type = text/javascript src = https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js></script>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<form action="http://127.0.0.1:1880/" target="_self">
    <label for="request"><strong>Please insert the input here:</strong></label><br>
    <input type="text" id="request" name="input"><br>
    <button v-on:click="getOverview($event)">Submit</button>
</form>
<h1 id="results" v-for="overview in overview">
    {{overview}}
</h1>
<script type = text/javascript >
    new Vue({
        el: "#results",
        data() {
            return {
                overview: []
            }

        },
        methods: {
            async getOverview(event) {
                try {
                    const {data:{json:{sub_regions}}} = await axios.get('http://127.0.0.1:1880/');
                    console.log('results data', sub_regions);
                    this.overview = sub_regions;
                }
                catch (error) {
                    console.log(error);
                    return [];
                }
            }
        },
        created(){
            this.getOverview()
        }
    })
</script>
</body>
</html>

I am new to JavaScript and feeling a bit overwhelmed by it, any help would be greatly appreciated. Thank you in advance! :)

EDIT: The file returned from the API is in JSON format

Answer №1

It seems like you are attempting to execute a method outside of the Vue app itself. Although you have specified el: "results", you are trying to call a Vue method from a button that is not within its context.

Please consider revising your code as follows:

<div id="results">
  <form action="http://127.0.0.1:1880/" target="_self">
      <label for="request"><strong>Please enter input here:</strong></label><br>
      <input type="text" id="request" name="input"><br>
      <button v-on:click="getOverview($event)">Submit</button>
  </form>
  <h1 v-for="overview in overview">
      {{overview}}
  </h1>
</div>

Answer №2

Encountering some issues...

  1. Make sure not to include Vue library twice (
    https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js
    and
    https://unpkg.com/vue/dist/vue.js
    ). It's unnecessary.
  2. Avoid using a v-for directive on the root Vue element.
  3. Your form should be within the Vue root in order to utilize v-on.
  4. The submit button will proceed with the default form submission behavior without any intervention.
  5. The value of your input field is not being utilized. Consider binding it to a data property.

Revise your HTML code as follows:

<div id="results">
  <form action="http://127.0.0.1:1880/" @submit.prevent="getOverview">
    <label for="request">
      <strong>Please enter input here:</strong>
    </label> 
    <br>
    <input type="text" id="request" name="input" v-model="input">
    <br>
    <button type="submit">Submit</button>
  </form>
  <h1 v-for="item in overview">
    {{ item }}
  </h1>
</div>

Replace data section in your JS with:

data: () => ({
  overview: [],
  input: ''
})

You can access user input value by using this.input.

Here's an example incorporating a placeholder API:

new Vue({
  el: "#results",
  data: () => ({
    overview: [],
    input: ''
  }),
  methods: {
    async getOverview ($event) {
      let url = 'https://jsonplaceholder.typicode.com/users'
      if (this.input) {
        url += `/${encodeURIComponent(this.input)}`
      }
      try {
        const { data: sub_regions } = await axios.get(url)
        console.log('results data', sub_regions);
        this.overview = Array.isArray(sub_regions) ? sub_regions : [ sub_regions ]
      } catch (error) {
        console.log(error);
        this.overview = []
      }
    }
  },
  created() {
    this.getOverview()
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div id="results">
  <form action="http://127.0.0.1:1880/" @submit.prevent="getOverview">
    <label for="request">
      <strong>Please insert the user ID here:</strong>
    </label>
    <br>
    <input type="number" id="request" name="input" v-model.number="input">
    <br>
    <button type="submit">Submit</button>
  </form>
  <h1 v-for="item in overview">
    {{ item.name }}
  </h1>
</div>


Additional Notes:

  • Avoid using the same variable name for array and iterable.

    • Incorrect -
      v-for="overview in overview"
    • Correct -
      v-for="thing in things"
  • VueResource is outdated. Update to the latest version (1.5.1) or consider alternative solutions.

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

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

What is the reason that the select option change event does not allow the use of "this" and event.target to access the selected value

Why is it difficult to obtain the selected value in a select option change event using this or event.target, and instead needing to use cumbersome code like $( "select option:selected" )? This issue arose when I needed to access certain data-* attributes ...

The Vuejs component I created is failing to display on my Blade View

I can't seem to render my Vuejs component in my blade view. Any idea what I might be doing wrong? The specific component causing issues is named "star-rating". Blade View <div class="container"> <div class="row"> <div class="col- ...

How do you attach events to slots without disrupting the layout of the content?

I have been working on creating a context menu component that relies on slots, and should be implemented like this: <template> <Contextmenu> <template #contextmenu> <!--customized context menu here--> <template> <templ ...

The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8 I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide. Data Object Structure data: functio ...

Discover the steps to incorporate an external JS file into Next.js 12

I am encountering an issue in my Next.js project when trying to import a local JS file. Here is the code snippet I am using: <Script type="text/javascript" src="/js.js"></Script> Unfortunately, this approach results in the ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Webpage push notifications are a convenient feature that allows websites to

Is it possible to incorporate web notifications on websites built using JSPs with jQuery, Vue, and Angular.js on the front end? Is there a method to integrate web notifications within this specific environment? ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

What is the reason behind Chrome's fullscreen mode turning the background black?

I created a webpage with full-screen functionality and made sure to use the correct CSS properties to ensure that my gradient background covers the entire screen perfectly. However, I encountered an issue when clicking the full-screen button in Chrome - th ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

Incorporate chat functionality into Angular using an embedded script

Recently, I encountered an issue with inserting an online chat using a Javascript script into my website. My initial plan was to add it directly to my app.component.html, but unfortunately, it didn't display as expected. I'm now exploring option ...

Should I choose JavaScript or TypeScript for Angular 2.0?

What is the best approach for creating an Angular 2.0 application? Should it be done with JavaScript or TypeScript? I'm struggling to get started with Angular 2.0 using TypeScript, as it's quite different from JavaScript. ...

Unable to successfully upload a .docx file within OnlyOffice utilizing JavaScript

Our application has successfully integrated the OnlyOffice editor. I am currently facing an issue while trying to upload a .docx file from my PC to the OnlyOffice server for later editing. Despite sending a POST request to the server using formdata, the fu ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code: <script> var newData = {}, graphs = [] for(var j=0; j<2; j++){ newData["name"] = 'value '+ j console.log(newData["name"]); graphs.push(newData); console.log ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...