【问题标题】:Vue.js cannot access elements within objectVue.js 无法访问对象内的元素
【发布时间】:2021-10-14 13:48:41
【问题描述】:

希望有人能给我解释一下..

我正在使用 axios 从网页中获取 json。我可以毫无问题地获取数据并将其输出到我的 html,但是当我尝试访问单个元素时出现错误“无法读取 null 的属性(读取 '0')”

这是我的 JS 代码:

//app.js
const app = {
  data() {
    return {
      quotes: null,
    }
  },
  mounted() {
    axios
      .get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/')
      .then(response => (this.quotes = response.data.quotes) )
  },
  methods: {
    test() {
      console.log(Object.keys(this.quotes))
      console.log(this.quotes)
    }
  }


}

Vue.createApp(app).mount('#app')

我可以像这样访问我的数据:

<!--index.html-->
...
<div id="app">
    <div>
      {{ quotes }}
    </div>
  </div>
...

哪个输出:

[ { "quote": "生活不是获得和拥有,而是给予和存在。", "author": "Kevin Kruse" }, ...]

但是当我尝试时:

<!--index.html-->
...
<div id="app">
  <div>
    {{ quotes[0] }}
  </div>
</div>
...

我收到错误消息:

未捕获的 TypeError:无法读取 null 的属性(读取 '0')

谁能帮助我了解如何访问我的引号对象中的单个元素?

【问题讨论】:

  • 请求需要一段时间才能完成,在此之前quotesnull。您的第一次尝试效果很好,因为{{ null }} 只会渲染任何内容,但您无法访问null 的“第一个元素”。使用conditional rendering 或类似{{ quotes &amp;&amp; quotes[0] }}
  • Suspense 也是如此。

标签: javascript vue.js


【解决方案1】:

您试图在初始化之前访问一个对象。试试:

<div id="app">
  <div v-if="quotes">
    {{ quotes[0] }}
  </div>
</div>

在第一次渲染发生时您的quotes === null。并且不可能做到null[0]。 在 API 调用之后,您将一个对象分配给 quotes,并且只有在重新渲染后您才能获得 quotes[0]

【讨论】:

  • 非常感谢 - 现在似乎很明显了:)
猜你喜欢
  • 2020-11-28
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多