Vue错误记录:ajax get后数组与对象的转换

api接口:

[{"comment_nums":2242816,"rank_year":2016,"rank":2,"url":"http://product.dangdang.com/23464478.html","book_name":"东野圭吾:解忧杂货店","author":"东野圭吾","publisher":"南海出版公司","price":39.5,"publish_time":"2014-05-01","recommend_percent":99.9,"front_image_path":"full/fe7db4bfb42c97a19b901cefea40142d19119217.jpg"}]

这里我希望get后把数据存在book对象中,以{{book.book_name}}输出书名。

错误代码:

<template>
  <div class="app-container">
    {{book.book_name}}
  </div>
</template>


<script>
import axios from "axios";
export default {
  data() {
    return {
      book: {}
    };
  },
  created() {
    this.fetchDataById()
  },
  methods: {
    fetchDataById() {
      var that = this;
      this.axios
        .get("http://127.0.0.1:8000/api/xxxxx").then(res => {
          that.book = res.data;
          console.log(that.book);
        }).catch(error => {
          console.log(error);
          this.dialogError = true;
        });
    }
  }
};
</script>

错误分析:

我一直以为api里传进来的只是一本书,必然是个对象,但没注意外面有个中括号! TAT

api里返回的是一个只有一个对象元素的数组。赋值语句that.book = res.data执行后的book是数组。故无法通过{{book.book_name}}输出数组中某一元素的书名。

法1:
通过循环数组输出:(虽然这个数组只有一个元素)

	<template>
	  <div class="app-container">
	    <div v-for="item in book" :key="item">
	      <p>{{item.book_name}}</p>
	    </div>
	  </div>
	</template>

法2:
js是弱类型,因此get后直接把数组第一个元素提出来赋值即可。

	fetchDataById() {
      var that = this;
      this.axios
        .get("http://127.0.0.1:8000/api/xxxxx").then(res => {
          that.book = res.data[0];
          console.log(that.book);
        }).catch(error => {
          console.log(error);
          this.dialogError = true;
        });
    }

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/105488805