Home > Back-end >  Calling a function to apply discounts before submitting the form in VUE.JS
Calling a function to apply discounts before submitting the form in VUE.JS

Time:12-10

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')"

CodePudding user response:

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()

CodePudding user response:

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()
  • Related