首页 > 解决方案 > javascript将对象解构为“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 }

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

标签: javascriptvue.jsobject-destructuring

解决方案


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

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

Object.assign(this, response.data);

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

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

推荐阅读