Vue.js:无法设置未定义的属性'profile_picture'

时间:2019-10-08 06:46:16

标签: vue.js

我真的很困惑我的代码有什么问题。有人可以告诉我我在这里做错了什么。

data() {
    return {
        users: [],
    }
},
methods:{
    moveData(response){
        for(var x=0;x<response.data.data.length; x++){
            this.users[x].profile_picture = response.data.data[x].profile_picture;
            this.users[x].age = response.data.data[x].age;
            this.users[x].intro = response.data.data[x].introMessage;
            this.users[x].name = response.data.data[x].userName;
        }
        // eslint-disable-next-line
        console.log('Users',this.users);
    }
}

2 个答案:

答案 0 :(得分:1)

,因为错误提示this.users[x]未定义。简单的解决方案是使用一些空对象初始化this.users[x],就像

for(var x=0;x<response.data.data.length; x++){
   this.users[x] = {};
   this.users[x].profile_picture = response.data.data[x].profile_picture;
   this.users[x].age = response.data.data[x].age;
   this.users[x].intro = response.data.data[x].introMessage;
   this.users[x].name = response.data.data[x].userName;
}

答案 1 :(得分:1)

使用this.users[x]时,由于数组长度为0,因此始终未定义。因此,这里还有一种方法可以使用.map()数组修改字段名称并将响应直接分配给{{1 }}在users中。

通过具有传播运算符的Map数组

moveData

在代码中进行修改,请使用push数组方法

const response = [{
  profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
  age: 25,
  introMessage: 'Hello',
  userName: 'test105'
}, {
  profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
  age: 18,
  introMessage: 'HI',
  userName: 'demo105'
}]

console.log(response.map(({age,profile_picture,...r}) => Object.create({
  age,
  profile_picture,
  name: r.userName,
  intro: r.introMessage
})));