David Meyers
David Meyers

Reputation: 21

Vue.js - Trouble displaying results from API call in component

Experimenting with Vue.js, trying to display results from a Wikipedia API call in a component using the v-for directive, but something is not working on the back end and I don't know what it is.

Link to the jsFiddle

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>"
});

The two issues on my mind are

When I look at the array in the console, all it shows are getters and setters. I'm new to this, so maybe that's what it's supposed to be doing.

I'm so close to getting this working, but I'm at my wits end, help is much appreciated.

Upvotes: 0

Views: 80

Answers (1)

Mark
Mark

Reputation: 92440

The problem with your code is that html tags aren't case sensitive so naming a component searchResult causes issues. If you need to use searchResult, you'll have to use <search-result> in your template. I find it better just to avoid the problem altogether and give components lower-case names. Here are docs about the issue: https://v2.vuejs.org/v2/guide/components.html#Component-Naming-Conventions

You mentioned "the error message that shows in the console when typing input". I didn't get any errors copying and pasting your code (other than forgetting to include axios). What error are you getting?

Upvotes: 0

Related Questions