【问题标题】:vuejs displaying API data using attribute bindingvuejs 使用属性绑定显示 API 数据
【发布时间】:2018-12-03 18:04:03
【问题描述】:

我有一个简单的应用程序,用户选择一个人,vue 对该用户的帖子进行 api 调用。这些帖子中的每一个都有自己的 cmets。这全部来自https://jsonplaceholder.typicode.com/ 评论部分始终为空。

密码笔是here

我的html

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id='app'>
<div v-if='isError'>
There was an error
</div>
<div v-else-if='isLoading'>
Loading
</div>
<div v-else>
 <select v-model="selectedUser">
      <option v-for="person in info" v-bind:value="person"> {{person.name}}</option>
 </select>
</div>
<div class="posts">
  <div v-if="isLoadingPosts">
  Loading...
  </div>
  <div v-else>
    <ul>
      <li v-for="post in postData">
      <p>
      {{ post.body }}
      </p>
       <button v-bind:id='post.id' v-on:click='getComments'>
      View Comments
      </button>
      </li>

    </ul>
  </div>
</div>
<div class="comments">
<p>
{{ commentData }}
</p>
</div>
</div>

JS 逻辑

var app = new Vue({
  el: '#app',
  data: {
    info : null,
    isLoading : true,
    isError : false,
    selectedUser : '',
    postData : null,
    isLoadingPosts : true,
    commentData : null,
  },
  watch : {
  selectedUser : function () {
  axios
  .get('https://jsonplaceholder.typicode.com/posts?userId=' + this.selectedUser.id)
  .then(response => (this.postData =response.data))
  .catch(error=> {console.log(error)})
  .finally(() => this.isLoadingPosts = false)
   }
  },
  methods : {
  getComments : function (){
    axios
        .get('https://jsonplaceholder.typicode.com/posts/' + this.id + '/comments')
      .then(response => (this.commentData =response.data))
  }
  },
  mounted () {
  axios
    .get('https://jsonplaceholder.typicode.com/users')
    .then(response => (this.info = response.data))
    .catch(error => {console.log(error);this.isError = true})
    .finally(() => this.isLoading = false)
  }
})

一切正常,除了 cmets 部分它总是返回一个空对象。我也觉得我的代码是重复的,任何更正将不胜感激。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    所以你对这个方法有几个问题:

    getComments : function (){
        axios
            .get('https://jsonplaceholder.typicode.com/posts/' + this.id + '/comments')
          .then(response => (this.commentData =response.data))
        }
      }
    

    首先,this.id 将在组件本身上查找 id 道具,而不是您尝试在按钮中绑定的 id。

    尝试将按钮代码更改为:

    <button v-on:click='getComments(post.id)'>View Comments</button>
    

    然后方法来:

      getComments : function (id){
        axios
            .get('https://jsonplaceholder.typicode.com/posts/' + id + '/comments')
          .then(response => (this.commentData =response.data))
        }
      }
    

    此外,您可能希望为其他 axios 调用添加一个 .catch() 处理程序,就像您的 id 一样。

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2016-02-04
      • 2021-01-23
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 2019-07-30
      相关资源
      最近更新 更多