【发布时间】:2018-01-26 08:35:22
【问题描述】:
我有这个 vue.js 组件,它使用 axios 检索 joke 对象的 json 数组:
<template>
<div id="show-jokes-all">
<h2>Showing all jokes</h2>
<div v-for="joke in jokes">
<h2>{{joke.title}}</h2>
<article>{{joke.body}}</article>
<hr>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'showJokes',
data () {
return {
jokes:[]
}
},
methods: {
},
created() {
axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){
//console.log(data); works fine
this.jokes = data.body;
});
}
}
</script>
当我在控制台中记录结果时很好,但是当我尝试将它放入 jokes 数组时,我得到了
Uncaught (in promise) TypeError: Cannot set property 'jokes' of 未定义
这可能是一个微不足道的错误,但作为 vue.js 的新手,我对此很了解,因此感谢您的提示。
【问题讨论】:
-
本质上是
.then(data => this.jokes = data.body),而不是你拥有的功能。或者使用上面链接中描述的闭包或绑定。 -
@Bert,我按照本教程进行操作,这就是它使用数据的方式:youtu.be/aoWqFLGCK60?list=PL4cUxeGkcC9gQcYgjhBoeQH7wiAyZNrYa
-
该教程使用 VueResource (
this.$http) 而不是axios。this在这两个库的回调中被区别对待。 -
对任何未来读者的澄清;我上面说的是
.then(data => this.jokes = data.body),但应该是.then(response => this.jokes = response.data)。
标签: javascript vue.js axios