繁体   English   中英

javascript将对象解构为'this'

[英]javascript destructure object to 'this'

我想将 response.data 的分页结果分配给 Vue 数据
所以显而易见的方法很简单

    this.data = response.data.data
    this.total = response.data.total
    this.perPage = response.data.per_page

但是有没有一种 ES6 方法可以将结果直接分配给这样的东西?

    const page = { data, total, per_page : perPage } = response.data
    this = { ...this, ...page }

注意:上面的代码不起作用。

不是this - this不能重新分配。

如果data对象包含这些属性,并且您将response.dataperPage属性更改为per_page ,那么您可以使用Object.assign

Object.assign(this, response.data);

如果data对象包含其他属性,或者您无法重命名per_page ,则:

const { data, total, per_page : perPage } = response.data
Object.assign(this, { data, total, perPage });

因此,从@CertainPerformance 的回答并研究如何从如何获取 javascript 对象属性的子集检索对象的子集属性

我得到了一个对象解构的有效解决方案。

    const page = (({ data, total, per_page: perPage }) => ({ data, total, perPage }))(response.data)
    Object.assign(this, page)

然而,代码并没有缩短或更容易阅读,所以我回到了显而易见的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM