Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint.

To access the jsFiddle link, click here

HTML

<div id="app">
<input type="text" v-model="searchTerm" v-on:keyup="getResults">
  <searchResult
    v-for="item in results"
    v-bind:result="item"
    v-bind:key="item.key"
  ></searchResult>
</div>

Javascript

new Vue({
  el: '#app',
  data: {
    api: "https://en.wikipedia.org/w/api.php?",
    searchTerm: 'Ron',
    searchDataString: "action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy",
    searchCall: this.api+""+this.searchDataString,
    results: []
  },
  methods: {
    getResults() {
        this.searchCall = this.api+"action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy";
      //console.log( this.searchCall ); 
      axios.post( this.searchCall )
      .then(response => { this.processResults(response.data) });
    },
    processResults(data) {
        //console.log( data );
        for(var i = 0; i < data[1].length; i++) {
        var resultItem = { key:i, link:data[3][i], name:data[1], description:data[2][i] };
        this.results.push(resultItem);
        console.log(resultItem);
      }
    }
  }
});

Vue.component( "searchResult", {
    props:['result'],
  template: "<a target='_blank' href='{{ result.link }}'><div class='search-result'><h3>{{ result.name }}</h3><p>{{ result.description }}</p><div></a>"
});

There are two main concerns on my mind:

  • The error message displayed in the console when typing input, and
  • The fact that the array of results is generating empty objects instead of passing the actual data.

Upon inspecting the array in the console, I notice that it only shows getters and setters. Being new to this, I'm uncertain if this behavior is expected.

I feel like I am very close to solving this issue, but I have reached my limit. Any assistance would be greatly appreciated.

Answer №1

Your code is running into an issue due to the fact that html tags are not case sensitive, causing conflicts when naming a component searchResult. To resolve this, consider using <search-result> in your template if you need to use searchResult. Another solution is to opt for lower-case names for components to avoid this problem altogether. For more information on this topic, refer to the following documentation: https://v2.vuejs.org/v2/guide/components.html#Component-Naming-Conventions

You mentioned encountering an error message in the console when entering input. Upon testing your code, I did not come across any errors (except for missing axios). Could you provide more details about the specific error message you are receiving?

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

How can I display only the y-axis values and hide the default y-axis line in react-chartjs-2?

Although I have some experience with chartjs, I am struggling to figure out how to hide the default line. To clarify, I have attached an image that illustrates the issue. I would like to achieve a result similar to this example: . My goal is to make it loo ...

A JavaScript variable... cannot access

Can anybody explain to me the reason behind this reference not functioning properly? let linkId = $(this).attr("data-id"); //retrieve the id data when a tag is clicked $(".wrapper").find("section[id=linkId]").css({"background-color": "red"}); ...

The animation speed of the jQuery hashchange event is set to zero, causing the animation

I'm facing an issue with jQuery where my animation inside a hashchange event is not smooth; it happens instantly when triggered. I'm looking for a way to make the animation smoother. jQuery( document ).ready(function() { jQuery(window).on(&a ...

Mastering the placement of script tags in your Next.js application with Next Script

I'm in the process of integrating a third-party script into my Next.js website. This particular script adds an iframe right below its corresponding script tag. Therefore, it is crucial for me to have precise control over the placement of the script ta ...

Executing commands following a JSON loop in jQuery

I'm experiencing an issue with jQuery. When my page loads, I fetch a JSON file and loop through its items. However, I am unable to attach any event listeners to the input button that is added. For instance, I want to display an alert message... It s ...

Utilizing Javascript to filter data across multiple columns in tables

I've been experimenting with the JavaScript code below to filter table rows. The original code is from w3schools, but I made some modifications to target all input values. It works well for filtering one column, however, when I try to input a value in ...

Is your Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript. Here is the code snippet that I experimented with: function genre_itemclick(item){ if(item.classList.contains('light_blue_border_button')) { ...

Javascript challenges for beginners in coding world

After running the code snippet, I encountered the following error messages: at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Fun ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

increasing the efficiency of exporting large amounts of data in Laravel to prevent timeout errors

I need to create a monthly report based on a database containing thousands of records. Sometimes, users may request reports spanning multiple months. With the current record size, a month's worth of data can exceed 5000 entries. Currently, I am utili ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Dragging objects on a map is done using jQuery and it causes them to bounce

Currently, I am working on implementing the JQuery Draggable feature. My idea is to create a map where I can attach image Divs to it dynamically using Jquery. So far, I have been successful in adding the Divs and making them draggable around the map effici ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

I am looking to save a collection of variables in an array and store it as a $_SESSION variable

Looking to store an array of variables as a $_SESSION variable in order to use it in another .PHP file and perform operations with it. The array: <script> var idArray = [18, 28, 31, 38, 41]; </script> What I attempted, but didn't suc ...

Is it possible to insert an image directly into the <img> tag without having to first send it to the server?

I've created an upload form that allows users to submit images: <form> <input accept="image/jpeg, image/gif, image/png" type="file" name="image" id="image" class="UploadInput" onchange="submitImageUploaderForm()"/> </form> Once t ...

Expand or collapse level 1 nodes with v-treeview component

I have created a special button in my tree view that has the ability to toggle open and close all nodes within it. The button code: <v-btn @click="toggleTreeview" /> Here is my v-tree markup: <v-treeview :value="x" @inpu ...

Updating Sailsjs Localization Settings

After working with Sails.js for a while, I am interested in finding out if it is possible to manually adjust the localization from the controllers based on the URL. For example, accessing http://example.com/en would display the English version, while http ...

Searching for the position of objects within a collection?

I am seeking the ability to parse through an object and allocate each of its available attributes to a variable. Within this scenario, there are four potential properties present in different objects - some containing all four while others may only have t ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...