Javascript 无法在Vue 2上设置实例属性&;Axios API调用
我使用Axios库在Vue 2.0中进行如下API调用Javascript 无法在Vue 2上设置实例属性&;Axios API调用,javascript,ajax,api,vuejs2,axios,Javascript,Ajax,Api,Vuejs2,Axios,我使用Axios库在Vue 2.0中进行如下API调用 axios.get(API_URL + '/products?country=' + code, {headers: { Authorization: 'Basic c3VyZWJ1ZGR5LWFwaS11c2VyOkFwaTQzMjJTdXJlYg==' }}) .then((response) => { console.log(response); //
axios.get(API_URL + '/products?country=' + code, {headers: { Authorization: 'Basic c3VyZWJ1ZGR5LWFwaS11c2VyOkFwaTQzMjJTdXJlYg==' }})
.then((response) => {
console.log(response);
//this.products = response.data;
})
.catch(function (error) {
console.log(error);
});
“this.products=response.data;”注释出来后,我得到了这样一个完美的回答:
当我想将服务器响应附加到this.products,以便在视图中输出时,我得到以下信息:
我可以访问密码和国家/地区等密钥,但无法访问详细信息数组
现在陷入困境,想不出还能做什么
我的数据对象如下所示:
data:
{
country: "",
countries: "",
product: "",
products: "",
country_selected: "",
product_selected: "",
singleProduct: "",
},
您在哪里运行您的
axios
请求?我已经模拟了一个基于你上面代码的快速演示,它似乎适合我?查看-->
请注意:
- 我正在将产品设置为空数组
- 在
lifecycle挂钩中调用mounted
axios
的上下文可能绑定到axios
,而不是Vue实例
以下是我的Vue特定代码:
// Generated via --> http://beta.json-generator.com/NyhG4qTDf
const API = 'https://api.myjson.com/bins/tbeuh'
const app = new Vue({
el: '#app',
data: {
products: []
},
mounted() {
axios.get(API).then((res) => {
this.products = res.data
})
}
})
您在哪里运行您的axios
请求?我已经模拟了一个基于你上面代码的快速演示,它似乎适合我?查看-->
请注意:
- 我正在将产品设置为空数组
- 在
mounted
lifecycle挂钩中调用axios
根据代码所在的位置,此的上下文可能绑定到axios
,而不是Vue实例
以下是我的Vue特定代码:
// Generated via --> http://beta.json-generator.com/NyhG4qTDf
const API = 'https://api.myjson.com/bins/tbeuh'
const app = new Vue({
el: '#app',
data: {
products: []
},
mounted() {
axios.get(API).then((res) => {
this.products = res.data
})
}
})
您应该使用空哈希值初始化产品
:{}
,但是这并不能解决您的问题,只会解决卫生问题。当您打印this.products.details
?@Saurabh If I console log console.log(this.products));在API调用之后,它返回一个空数组。此.products.details未定义。我不确定它为什么不分配属性。反应性getter是由Vue添加的,这就是它观察更改并对更改作出反应的方式。当您在该输出中单击details(…)
时,您会看到什么?您应该使用空哈希初始化products
,{}
,但是这不会解决您的问题,只会解决卫生问题。当您打印this.products.details
?@Saurabh如果我控制台log console.log(this.products));在API调用之后,它返回一个空数组。此.products.details未定义。我不确定它为什么不分配属性。反应性getter是由Vue添加的,这就是它观察更改并对更改作出反应的方式。当您在该输出中单击details(…)
时,您会看到什么?我要求API开发人员更改API的结构。我遇到的问题是,在视图中,我无法访问details数组。我怀疑它在视图中是以字符串形式输出的,因此没有看到数组形式的细节?!我要求API开发人员更改API的结构。我遇到的问题是,在视图中,我无法访问details数组。我怀疑它在视图中是以字符串形式输出的,因此没有看到数组形式的细节?!