【发布时间】: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')
谁能帮助我了解如何访问我的引号对象中的单个元素?
【问题讨论】:
-
请求需要一段时间才能完成,在此之前
quotes是null。您的第一次尝试效果很好,因为{{ null }}只会渲染任何内容,但您无法访问null的“第一个元素”。使用conditional rendering 或类似{{ quotes && quotes[0] }} -
Suspense 也是如此。
标签: javascript vue.js