Error: Unable to submit data as the function this.submitData is not recognized

Having trouble calling an async function in the mounted() lifecycle hook of Vue.js? Keep getting the error message: Uncaught TypeError: this.submitData is not a function. Here's the code snippet in question:

<template>
    <section class="section-b-space">
        <div class="container">
            <div class="row">
                <div class="col-lg-3 category-side col-md-4">
                    <div class="category-option">
                        <div class="accordion category-name" id="accordionExample">
                            <div class="accordion-item category-price">
                                <h2 class="accordion-header" id="headingFour">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseFour">Price</button>
                                </h2>
                                <div id="collapseFour" class="accordion-collapse collapse show"
                                    aria-labelledby="headingFour" data-bs-parent="#accordionExample">
                                    <div class="accordion-body">
                                        <div class="range-slider category-list">
                                            <input type="text" class="js-range-slider" id="js-range-price" value="">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="accordion-item category-rating">
                                <h2 class="accordion-header" id="headingOne">
                                    <button class="accordion-button" type="button" data-bs-toggle="collapse"
                                        data-bs-target="#collapseSix">
                                        Category
                                    </button>
                                </h2>
                                <div id="collapseSix" class="accordion-collapse collapse show"
                                    aria-labelledby="headingOne">
                                    <div class="accordion-body category-scroll">
                                        <ul class="category-list">
                                            <li v-for="category in categories">
                                                <div class="form-check ps-0 custome-form-check">
                                                    <input class="checkbox_animated check-it" 
                                                        type="checkbox" @change="submitData" v-model="formData.category">
                                                    <label class="form-check-label">{{category.name}}</label>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import axios from 'axios';
export default{
    props:{
        categories: {
            default: []
        },
    },
    data(){
        return {
            formData:{
                category: [],
                price: '',
            },
        }
    },
    methods: {
        async submitData(){
            try{
                const response = await axios.post('/api/category', this.formData)
                console.log(response);
            }
            catch(error){
                console.log(error)
            }
        },
    },
    mounted() {
        $(".js-range-slider").on('change', () => {
            this.submitData()
                .then((res) =>{
                    console.log(res);
            })
                .catch((err) =>{
                    console.log(err);
            });
        });
    }
}
</script>

This vue file is specifically tailored for use with Vue.js and is utilizing version 3.

Answer №1

Examining the code below:

mounted() {
  $(".js-range-slider").on('change', function() {
    this.submitData()
      .then((res)=>{
         console.log(res);
      })
      .catch((err)=>{
        console.log(err);
      });
  });
}

It is evident that a listener has been attached to the 'change' event on an element with the js-range-slider class using a function callback.

An important point to remember is that when using function() { }, the callback will have its own this value, which refers to the element where the listener was attached (allowing access to properties like this.value).

To maintain access to the this from the mounted() method, you can take one of the following actions:

  1. Switch to an arrow function for your callback:
mounted() {
  $(".js-range-slider").on('change', () => {
    this.submitData() // `this` is inherited from `mounted()`
  1. Save the this reference from mounted() and use it inside the callback:
mounted() {
  const instance = this;
  $(".js-range-slider").on('change', function() {
    instance.submitData()

Makes sense?

  1. Pass the this from mounted() as data in the event listener:
mounted() {
  $(".js-range-slider").on('change', { component: this }, function(event) {
    event.data.component.submitData()

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

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

Having trouble with the sendFile function in your Node app built with Express?

Within my server.js file (where 'app' is an instance of express), I have the following code snippet. It is meant to send back a file named index.html which resides in the same directory as the server.js file. app.get('/', function (req ...

How can I add a black-colored name and a red-colored star to the Placeholder Star as a required field?

I'm looking to customize the placeholder text in an input field. I want the main placeholder text to be in black and have a red star indicating it's a required field. However, my attempt to set the color of the star specifically to red using `::- ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

Vue app encountering no response from Facebook Graph API

Can anyone help me troubleshoot an issue with a component I'm working on? I am trying to display photos from a Facebook Photo Album. When I click the button, it logs 'Button pressed' in the console but nothing else appears. Any suggestions o ...

encountering difficulties with parsing JSON data within JQuery script on Laravel 5.2

In my Laravel project, I am attempting to dynamically populate a second dropdown menu based on the value selected in the first dropdown. This process involves using AJAX to update the options available in the second dropdown when a Cinema Hall is selected. ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

Press the 'enter' button to post your tweet with Greasemonkey

I am working on a Greasemonkey script that will automatically submit a tweet when the user presses the 'enter' key. The script works perfectly on a basic HTML page with some help from tips I found on this website. However, when I attempt to use t ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Generating a stacked array using JavaScript

I have an original two-dimensional array representing the full budget for each year, as shown below: budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]] Now I want to create subarrays of the budget ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

React HTML ignore line break variable is a feature that allows developers to

Can you help me with adding a line break between two variables that will be displayed properly in my HTML output? I'm trying to create an object with a single description attribute using two text variables, and I need them to be separated by a line b ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...

The spring submission function requires the use of two parameters

As a beginner in spring web applications, I am facing an issue where the request mapping receives a "dual" parameter when I submit a form. The form structure is as follows: <form action="" method="post" name="myform"> ...... </form> To submit ...

What are the steps to utilize the "@" shortcut in webpack configuration?

After running "npm run build" with my package.json, I encountered the following message: How can I use '@' with webpack? ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector. js?type=script&index=0!./src/App. ...