[英]How can I use this in the left side of the object destructuring assignment?
(This question is not specific to Vue, but it is in a Vue project, that is why the strange use of the this
in front of the functions and variables.) (此问题并非特定于Vue,而是在Vue项目中,这就是为什么在函数和变量之前奇怪地使用
this
原因。)
I have a function that returns an object which is destructured into two variables: 我有一个函数,该函数返回一个被分解为两个变量的对象:
const { primaryNumber, typeOfExpression } = this.findPrimaryAndType(
this.naturalExpressionYearOfBirth,
this.gender,
);
I don't want the variables to be primaryNumber
and typeOfExpression
any more, I want them to be this.primaryNumber
and this.typeOfExpression
which refer to my view data section. 我不希望变量成为
primaryNumber
和typeOfExpression
,我希望它们成为this.primaryNumber
和this.typeOfExpression
,它们引用了我的视图数据部分。
I have found a crummy workaround using the code below: 我发现使用下面的代码一个糟糕的解决方法:
this.primaryNumber = primaryNumber;
this.typeOfExpression = typeOfExpression;
But this can't be the best way of doing it! 但这不是最好的方法! What should I do?
我该怎么办? If I add
this
in front of the variables inside the {}
I get an error and if I remove the const it does not accept the =
Thanks. 如果我加入
this
在变量的前内{}
我得到一个错误,如果我删除常量不接受=
感谢。
You can spell out the destructuring targets, instead of implicitly creating const
variables: 您可以阐明解构目标,而不是隐式创建
const
变量:
({
primaryNumber: this.primaryNumber,
typeOfExpression: this.typeOfExpression
} = this.findPrimaryAndType(
this.naturalExpressionYearOfBirth,
this.gender,
));
Of course that's not very helpful in terms of conciseness. 当然,就简洁而言,这不是很有帮助。 If those two properties are the only ones on the result object, you can however use
Object.assign
: 如果这两个属性是结果对象上唯一的属性,则可以使用
Object.assign
:
Object.assign(this, this.findPrimaryAndType(
this.naturalExpressionYearOfBirth,
this.gender,
));
Your workaround is the correct way to do this (at least from a pure Javascript perspective, not sure how Vue handles this). 解决方法是执行此操作的正确方法(至少从纯Javascript角度来看,不确定Vue如何处理此问题)。 You can make it slightly shorter by using
Object.assign
: 您可以使用
Object.assign
将其缩短一些:
const { primaryNumber, typeOfExpression } = this.findPrimaryAndType(
this.naturalExpressionYearOfBirth,
this.gender,
);
Object.assign(this, { primaryNumber, typeOfExpression });
Or, if you wanted to copy all the returned properties from findPrimaryAndType
to the current instance, you could skip the destructuring altogether: 或者,如果要将所有返回的属性从
findPrimaryAndType
到当前实例,则可以完全跳过解构:
const { naturalExpressionYearOfBirth, gender } = this;
Object.assign(this, this.findPrimaryAndType(naturalExpressionYearOfBirth, gender));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.