Gibson
Gibson

Reputation: 2085

Calling a function to apply discounts before submitting the form in VUE.JS

I need to apply corresponding discounts to each item in my campaign.items before submitting my form with Axios.

For this, I have a function that works correctly:

  applyDiscount(price) {
    return price - (this.totalDiscount * price)
  },

I'm placing the function call inside my submit function before submitting:

 methods: {
  submit() {
    this.campaign.items.forEach(function(item) {
        this.applyDiscount(item.price)
    }),
    var data = new FormData()

I'm getting the error:

Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'applyDiscount')"

Upvotes: 1

Views: 55

Answers (2)

Put that sock away
Put that sock away

Reputation: 162

I would have done the same, I suppose the "global" this is not equal to the component this.

An arrow function should work,

 methods: {
  submit() {
    this.campaign.items.forEach((item) => {
        this.applyDiscount(item.price)
    }),
    var data = new FormData()

Upvotes: 1

dave
dave

Reputation: 64705

The issue is that this inside of your anonymous function isn't the same as this outside of it. Typically what you can do is to get a reference to this before, by doing let that = this; and then use that inside of the other function:

class Demo {
    applyDiscount() {
        console.log('hi');
    }
    example() {
        var that = this;
        [1,2].forEach(function() {
            that.applyDiscount();
        })
    }
}

let x = new Demo();
x.example()

or you can bind this:

class Demo {
    applyDiscount() {
        console.log('hi');
    }
    example() {
        [1,2].forEach((function() {
            this.applyDiscount();
        }).bind(this))
    }
}

let x = new Demo();
x.example()

or you can use an arrow function:

class Demo {
    applyDiscount() {
        console.log('hi');
    }
    example() {
        [1,2].forEach(() => {
            this.applyDiscount();
        })
    }
}

let x = new Demo();
x.example()

Upvotes: 1

Related Questions