Using VUE.JS to trigger a function that applies discounts prior to form submission

Before submitting my form with Axios, I am in need of applying specific discounts to each item within campaign.items.

To achieve this, a functional method has been created:

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

Prior to submission, I am integrating the call to this function inside my submit function:

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

An error message is being displayed as follows:

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

Answer №1

The main problem arises when this inside the anonymous function differs from the outer scope's this. One common solution is to create a reference to this beforehand, like so: let that = this;, and then utilize that within the inner function:

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

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

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

Another option is to use an arrow function:

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

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

Answer №2

I might have made a similar choice, as it seems that the "universal" this is not equivalent to the specific this.

An arrow function could potentially resolve this issue,

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Increase the count if the item is already in the shopping cart - React

Is there a way to avoid adding the same product to the basket multiple times and instead just increment a counter? How can I effectively keep track of each item's count? this.state = { description: '', commaSalesPrice: '', ...

Clicking on React Js reverses an array that had previously been unreversed

My issue involves an array pulled from a database that I have reversed so that the newest entry is displayed at the top when a button is clicked, opening a modal-style window. However, when the array is displayed in the modal window, it appears to be flipp ...

Interactive Geography Selector

When updating your personal details on , you are required to choose your country first. Once the country is selected, the system automatically adjusts the city and/or state options based on that specific country's requirements. Can someone provide exa ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

Selenide is failing to remove elements with the displayed property set to false

On my automation tests, I am struggling to click a radio button. Even though the radio buttons are visible on the page, the unselected ones have the property displayed:false. Selenide seems unable to click if an html object has the displayed:false property ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

Steps for integrating Vue component into Laravel Framework

Encountering a problem with my Laravel + Vue Project. The error message is as follows: [Vue warn]: Unknown custom element: <packages> - have you correctly registered the component? Make sure to provide the "name" option for recursive compon ...

Challenges Arising from CGI Scripts

One requirement for the user is to input text into a designated text field within a form element in my HTML. Following this, a CGI script processes the user's input and JavaScript code is responsible for displaying the processed information. JavaScri ...

Is it not possible to access the profile page using the GET method?

I am currently using Express.js to display user input in the URL after submitting a form and redirecting the user to their profile page with their name in the URL. To achieve this, I utilized req.query and the GET method. var express = require('expre ...

Attempting to show the name in AngularJS

I've been working on mastering Angular JS, but I'm facing a challenge with displaying the user I just added to the database on the next page. While I can display other users, the newly added user's data just won't show up! I've tri ...

Dealing with jQuery's AJAX time conflicts

I've been tirelessly searching for a solution and spending hours on this issue. Essentially, I'm making an Ajax call to retrieve data from a webpage that in turn fetches data from a database. This particular code is designed for a slideshow featu ...

What is the best way to ensure a CSS element maintains its position margins even after adjusting them with JavaScript?

Currently, I am in the process of developing a minesweeper game using a combination of HTML, CSS, and JavaScript. The code snippet I am utilizing to generate the grid is as follows: <div id="game-space"></div> <script type="t ...

Retrieving arrays in subdocuments with MongoDB queries

Being a novice in the realm of mongodb, I welcome any corrections if my terminology is incorrect: The document snippet below showcases some information: { "_id" : ObjectId("524b0a1a7294ec8a39d4230f"), "name" : "Irbesartan", "decompositions" ...

Using v-autocomplete to store and display user input

I am currently using vuetify in my project and I am in need of a typeahead component. Unfortunately, v-autocomplete is implemented as a combobox with a filter, which does not allow for setting user input as the v-model (or at least I haven't been able ...

Markers on the map are not receiving the necessary click event handlers

The block of code below is designed to place markers on a map. However, it seems that the add Listener event is not properly attached to each marker. var mapDiv = document.getElementById("google-map"); var infoWindow = new google.maps.InfoWindow({ ...

What is the best way to retrieve the current URL with a hashtag symbol using JavaScript?

I am attempting to display the current URL after the question mark with a hash symbol using PHP, but unfortunately, it is not achievable. Therefore, I need to utilize JavaScript for this task, even though I have limited knowledge of it. This is the specifi ...

SwiperJs: I'm struggling to align groups of 2 slides in the center because I am unable to limit the width of the slides

I am currently working on a project involving SwiperJS to create a slider that showcases two slides per group, neatly centered within the container of the slider. Despite my best efforts, I have encountered an issue where the slides expand to occupy the en ...

Differences in performance between Angular and JQuery_execution times

I am facing an issue on my dynamically populated Angular page. Angular sends a request to the backend using $http.get to retrieve data which then populates attributes of a controller. For example, when I call $http.get('/_car_data'), the JSON re ...

Generate projectiles within a game periodically

I've created a game that features a main character and enemy soldiers who shoot back. I'm facing an issue where only one enemy soldier shoots at intervals, even though I initially used setInterval for both of them. Any suggestions on how to fix t ...

Issue with the side panel: unable to close it

There seems to be an issue with the close button on the sidebar—it's neither displaying nor functioning properly. The show sidebar feature works perfectly fine, but there is a problem with the closing function. Below is the HTML, CSS, and JavaScript ...