显示来自api VueJS的数据

时间:2020-05-12 11:38:51

标签: api vue.js axios

我正在使用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"}]}

1 个答案:

答案 0 :(得分: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);
     });
    }
  }
}