从对象vuejs数组中获取第一个对象



如何获取对象第一个对象id的数组

这是我的arrray内容

0:{id:1,user_id:1,user2_id:2,created_at:"2021-03-22T16:37:10.000000Z",…}

1:{id:7,user_id:1,user2_id:3,created_at:"2021-03-24T16:24:47.000000Z",…}

2:{id:8,user_id:1,user2_id:1,created_at:"2021-03-24T18:19:21.000000Z",…

<script>
export default 
{    
data(){
return{
convs_id: [],
convs: [],
}

},

created(){

this.fetchConversation();
this.convs_id = this.convs[0].id;
console.log(this.convs_id);
},
methods:
{
fetchConversation()
{
axios.get('getConvs').then(response=>{
this.convs = response.data;

});

}
}
}

this.convs在获取数据的调用解析后被填充。因此,为了使用它,你必须等待这个承诺得到解决。

为了能够等待承诺,你必须return。因此fetchConversation()需要返回axios.get()(这是你将要等待的承诺(:

methods:{
fetchConversation() {
return axios.get('getConvs').then(response => {
this.convs = response.data;
});
}
}

现在,fetchConversation()返回promise,有两种方法可以等待它:要么使createdasync,要么使用await:

async created() {
await this.fetchConversation();
console.log(this.convs[0]);
}

或者调用promise上的.then()方法:

created() {
this.fetchConversation().then(() => {
console.log(this.convs[0]);
})
}

在请求成功回调中提取第一项:

export default 
{    
data(){
return {
convs_id: null,
convs: [],
}
},
created(){
this.fetchConversation();

},
methods:
{
fetchConversation()
{
axios.get('getConvs').then(response=>{
this.convs = response.data;
let [firstConvs]=this.convs;// es6 syntax of destructing the array
this.convs_id = firstConvs.id;

});

}
}
}

最新更新