3

How can I use object destructuring to my Vue component data? This is my actual code:

data: () => ({
  descricao: '',
  perfilBase: null,
  anotherField: '',
  otherOne: false
}),

mounted () {
  this.descricao = this.$route.query.descricao
  this.perfilBase = this.$route.query.perfilBase
}

How can I do it like this? Is it possible?

mounted () {
  { this.descricao, this.perfilBase } = ...this.$route.query
}
Fantasmic
  • 1,122
  • 17
  • 25

3 Answers3

5

To use destructuring with targets other than simple variables, you cannot use the shorthand syntax but need to specify the destructured property name explicitly. In your case:

mounted () {
  ({ descricao: this.descricao, perfilBase: this.perfilBase } = this.$route.query);
}

However, if the query object contains only those two properties, Object.assign is a much simpler solution:

mounted () {
  Object.assign(this, this.$route.query);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I think the first example becomes useful when changing from one case style to another, like this: `({ order_number: this.orderNumber, order_amount: this.orderAmount } = this.config);` – Giorgio Tempesta Mar 22 '21 at 14:40
4

I don't think there's a way to be as succinct as you want to be.

The best thing you can do is probably

mounted () {
   const { descricao, perfilBase } = this.$route.query
   this.descricao = descricao
   this.perfilBase = perfilBase
}
Axnyff
  • 9,213
  • 4
  • 33
  • 37
4

Check if this works, i am not behind my computer right now.

{ a, b } = this.$route;
[ this.a, this.b ] = [a, b];
yooneskh
  • 784
  • 7
  • 11