在Vue中,this和object如何解构赋值
我们经常会碰到在vue中需要把一个传进来的对象赋值到当前组件上,例如
this.date= res.date; this.avatar=res.avatar; this.userID=res.userID this.username=res.username;
2021年新增
data(){
username:"",
userID:"",
avatar:"",
date:""
}
mounted(){
axios.get().then(res=>{
Object.assign(this._data, res)
})
}
附assign文档—
第一种解决办法是先声明一个容器,然后把接收对象直接挂到容器上
data(){
res:{
}
}
mounted(){
axios.get().then(res=>{
this.res=res
})
}
第二种方法是使用forEash
data(){
username:"",
userID:"",
avatar:"",
date:""
}
mounted(){
axios.get().then(res=>{
["date","userID","username","avatar"].forEach((key)=>{
if(key in res){
this[key]=res[key]
}
})
})
}
最后附一个forEach的MDN
