javascript - vuejs 使用属性绑定(bind)显示 API 数据

标签 javascript vue.js axios

我有一个简单的应用程序,用户选择一个人,vue 为该用户的帖子进行 api 调用。每个帖子都有自己的评论。这全部来自 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)
  }
})

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

最佳答案

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

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

首先,其中的 this.id 将在组件本身上查找 id 属性,而不是您尝试在按钮中绑定(bind)的 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 一样。

关于javascript - vuejs 使用属性绑定(bind)显示 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599359/

相关文章:

javascript - Reactjs 与 Parse.com 异步加载错误?无法访问对象

javascript - 如何避免视差性能问题?

javascript - 将变量放入 onclick 定义中是否安全?

javascript - 如何在对象中使用 Vue watch

vue.js - 如何每 x 秒调用一个方法?

javascript - 下拉菜单的 javascript onclick 问题

typescript - 异步函数的返回类型必须是全局 Promise<T> 类型

javascript - 如何使用 VueJS 将来自 API 的数据存储在 localStorage 中

javascript - axios.all的动态使用

javascript - Vue.js crud javascript?