0

In a Vue component, I have a method like as below

methods: {
   submitMethod() {
     let objA = {
       id: this.id,
       this.anObject
     }
   }
 }

It gives, Syntax Error: this is a reserved word.

how to use the object, which is defined in somewhere like data() or computed, in the object of the method in Vue.js?

One workaround is that, this.anObject can be assigned to local variable and use that variable inside objA as below

submitMethod() {
    let anObject = this.anObject
    let objA = {
        id: this.id,
        anObject
     }
}

But, is there a way to use this.anObject directly inside objA?

3 Answers 3

1

If you can use the object restSpread operator, you can use it:

methods: {
   submitMethod() {
     let objA = {
       id: this.id,
       ...this.anObject
     }
   }
 }

Otherwise, you can use Object.assign:

methods: {
   submitMethod() {
     let objA = Object.assign(this.anObject, {
       id: this.id,
     })
   }
 }
Sign up to request clarification or add additional context in comments.

Comments

0

thats because your JSON is invalid. it should be like

let objA = {
    id: this.id,
    anObject: this.anObject
}

Comments

0

We can use this keyword with the help of copy this keyword as a local variable.

methods: {
  submitMethod() {
    let _this = this;
    let objA = Object.assign(this.anObject, {
       id: _this.id,
    })
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.