Javascript 如何使用Vue获取json并获取Api
我有一个基于Vue.js的简单代码:Javascript 如何使用Vue获取json并获取Api,javascript,vue.js,Javascript,Vue.js,我有一个基于Vue.js的简单代码: const app = new Vue({ el: 'vue-app', data: { displayedBooks: {} }, created() { fetch('/library').then(response => response.json()) .then((data) => this.data.displayedBooks = data);
const app = new Vue({
el: 'vue-app',
data: {
displayedBooks: {}
},
created() {
fetch('/library').then(response => response.json())
.then((data) => this.data.displayedBooks = data);
}
});
但我有一个例外:
未捕获(承诺中)TypeError:无法在fetch.then.then(main.js:8)设置未定义的属性“displayedBooks”
为什么这个简单的代码不能很好地工作?应该是
这个.displayedBooks
,而不是这个.data.displayedBooks
。Vue数据参数中的所有内容都直接连接到该参数
const-app=新的Vue({
el:“vue应用程序”,
数据:{
显示的图书:{}
},
创建(){
获取('/library')。然后(响应=>{
this.displayedBooks=response.data
},错误=>{
console.log(错误)
})
});
它应该是this.displayedBooks
,而不是this.data.displayedBooks
。Vue中的所有数据
参数都直接附加到this
上。这是一个简单的输入错误:它应该是this.displayedBooks=data
:)另一个问题可能是“this”在this.data.displayedBooks中可以是Ajax库,而不是Vue实例。如果这是问题所在,请定义:var vm=this;然后使用vm.data.displayedBooks返回数据的位置。在注释中,a获得了所有答案!使用this.displayedBooks
,不要忘记在var self=this
存储上下文ode>created()函数