我正在尝试将对象添加到数组中,但无法正常工作,程序无法读取属性 push
我在<script>
中定义了一个数组:
Data: function() {
return {
Projects: [
{
name: '',
id: 0,
subscribers: 0,
products: {name:'',color:''},
}
],
}
在函数中:
GetAllWorkspaces: function(){
var app = this;
const instance = axios.create({
timeout: 1000,
headers: {
........
}
});
instance.get("XXXXXXX")
.then( function(response) {
console.log(response);
Object.keys(response.data.result).forEach( function (product) {
var subscribersCounter = 0;
let example = {
name: response.data.result[product].name,
id: response.data.result[product].id,
subscribers: response.data.result[product].subscribers,
products: response.data.result[product].products,
};
let uploadedExample = {
name: '',
id: '',
subscribers: '',
products: {name:'',color:''},
};
uploadedExample.name = example.name;
uploadedExample.id = example.id;
if ( example.subscribers ) {
Object.keys(example.subscribers).forEach(function (key) {
subscribersCounter++;
});
}
uploadedExample.subscribers = subscribersCounter;
if ( example.products ) {
Object.keys(example.products).forEach(function (Pkeys) {
uploadedExample.products.name = Pkeys;
Object.keys(example.products[Pkeys]).forEach(function (key) {
if (key == 'color') {
uploadedExample.products.color = example.products[Pkeys][key];
}
});
});
}
//add the new workspace to the list of workspaces.
app.Projects.push(uploadedExample);
});
})
.catch(function(error) {
console.log(error);
});
我的问题是这条线
app.Projects.push(uploadedExample);
当我尝试将对象推入数组时,将显示错误消息:
TypeError:无法读取未定义的属性“ push”
答案 0 :(得分:1)
如错误所述,问题是app.Projects未定义。发生这种情况是因为'this'是指GetAllWorkspaces内的函数作用域,而不是组件范围(您可以通过console.log尝试使用它。无论如何,这是一个好习惯,因为'this'可以随上下文而变化上下文)。如果要将组件范围保留在方法中,则应使用如下箭头函数:
GetAllWorkspaces: () => {
// do all your stuff
}