【问题标题】:Displaying data from api VueJS显示来自 api VueJS 的数据
【发布时间】:2020-08-28 05:41:44
【问题描述】:

我正在使用 axios 从 api 获取数据,当我 console.log(app.books) 可以看到我的数据但它不会显示在页面上。我正在使用 v-for 在表格上显示数据。 我很困惑我的代码出了什么问题?

<tbody>
  <tr v-for="book in books" class="text-center">
    <td> {{ book.id }} </td>
    <td><a href="#"> {{ book.name }} </a></td>
    <td> {{ book.author }} </td>
    <td> ${{ book.price}} </td>
    <td>
      <a href="#" class="text-success" @click="showEditModal=true">
        <i class="fas fa-edit"></i> 
      </a>
    </td>
    <td>
        <a href="#" class="text-danger" @click="showDeleteModal=true">
          <i class="fas fa-trash"></i>  
      </a>
    </td>
  </tr>
</tbody>

export default {
  name: "App",
  data: function() {
    return {
      successMsg: false,
      errorMsg: false,
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      books: [],
      newBook: {name: "", author: "", price: ""},
      currentBook: {}
    }
  },
  mounted: function(){
    this.getAllBooks();
  },
  methods: {
    getAllBooks: function(){
      axios.get('http://localhost/crud-vuejs/src/Backend/api.php?action=read')
     .then(function(res) {
        if(res.data.error){
          app.errorMsg = res.data.message;
        }
        else{
          app.books = res.data.books;
        }
        console.log(app.books);
     });
    }
  }
}

响应负载:

{"books":[{"id":"1","name":"Harry Potter","author":"J. K. Rowling","price":"40"},{"id":"2","name":"The great gastby","author":"Scott Fitzgerald","price":"36"},{"id":"3","name":"To Kill a Mockingbird","author":"Harper Lee","price":"26"}]}

【问题讨论】:

    标签: api vue.js axios


    【解决方案1】:

    您应该将app 替换为this

    export default {
      name: "App",
      data: function() {
        return {
          successMsg: false,
          errorMsg: false,
          showAddModal: false,
          showEditModal: false,
          showDeleteModal: false,
          books: [],
          newBook: {name: "", author: "", price: ""},
          currentBook: {}
        }
      },
      mounted: function(){
        this.getAllBooks();
      },
      methods: {
        getAllBooks: function(){
          axios.get('http://localhost/crud-vuejs/src/Backend/api.php?action=read')
         .then((res) => {
            if(res.data.error){
              this.errorMsg = res.data.message;
            }
            else{
              this.books = res.data.books;
            }
            console.log(this.books);
         });
        }
      }
    }
    

    【讨论】:

    • 我确实替换了它,但后来出现错误“这是未定义的”
    • 是的,你是对的。我更新了答案。在then promise 块中,您正在创建一个新的本地函数作用域。我用一个粗箭头函数替换了它,现在它应该可以工作了。 (res) =&gt; { ... }
    • 所以都是关于箭头函数的
    猜你喜欢
    • 2019-05-06
    • 2018-02-07
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2020-09-29
    相关资源
    最近更新 更多