【问题标题】:Vue.js - Trouble displaying results from API call in componentVue.js - 无法在组件中显示 API 调用的结果
【发布时间】:2017-10-20 16:52:24
【问题描述】:

使用 Vue.js 进行实验,尝试使用 v-for 指令在组件中显示来自 Wikipedia API 调用的结果,但后端无法正常工作,我不知道它是什么。

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

我想到的两个问题是

  • 输入输入时控制台中显示的错误消息,以及
  • 结果数组正在创建空对象而不是传递数据

当我在控制台中查看数组时,它显示的只是 getter 和 setter。我是新手,所以也许这就是它应该做的。

我已经接近完成这项工作了,但我束手无策,非常感谢您的帮助。

【问题讨论】:

  • 检查小提琴链接,它只有初始的Vue代码。
  • @yuriy636 糟糕,我保存了它。现在应该显示。

标签: javascript vue.js


【解决方案1】:

您的代码的问题在于 html 标记不区分大小写,因此将组件命名为 searchResult 会导致问题。如果您需要使用searchResult,则必须在模板中使用&lt;search-result&gt;。我发现完全避免这个问题并给组件小写名称会更好。以下是有关该问题的文档:https://vuejs.org/v2/guide/components.html#Component-Naming-Conventions

您提到了“输入输入时在控制台中显示的错误消息”。复制和粘贴您的代码时,我没有收到任何错误(除了忘记包含 axios)。你遇到了什么错误?

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 2021-01-25
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2018-03-08
    相关资源
    最近更新 更多