skip to Main Content

I have defined a async function in methods and when trying to call the same function in mounted.. it is giving the error – Uncaught TypeError: this.submitData is not a function.
Please help me out how to call async function in mounted() in vue js. Below is my code –

<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', function(){
                this.submitData()
                    .then((res)=>{
                        console.log(res);
                })
                    .catch((err)=>{
                        console.log(err);
                });
            });
        }
    }
</script>

This is .vue file and i am using vue3

2

Answers


  1. You should have a Promise and organize the service, like this:

    const service = {
        async submitData(){
            return new Promise((resolve, reject) => {
                try {
                    const response = await axios.post('/api/category', this.formData)
                    // more treatments here
                    resolve(response);
                }
                catch(error){
                    reject(error)
                }    
            });
        },
        mounted() {
            service.submitData()
                .then((res)=>{
                    console.log(res);
                })
                .catch((err)=>{
                    console.log(err);
                });
        }
    };
    
    export default service;
    
    Login or Signup to reply.
  2. Looking at the following lines:

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

    We can see that you’ve attached a listener to the ‘change’ event to an element with the js-range-slider class using a callback defined with function.

    An important thing to note here is that when using function() { }, the callback will have its this value set to the element on which the listener was attached (so you can use things like this.value to get the current value).

    To maintain access to the this from mounted(), which is your initialized component, you can do one of the following:

    1. Change to an arrow function for your callback:
    mounted() {
      $(".js-range-slider").on('change', function() {
        this.submitData()
    

    becomes

    mounted() {
      $(".js-range-slider").on('change', () => {
        this.submitData() // `this` is inherited from `mounted()`
    
    1. Store the this from mounted() and use that value instead:
    mounted() {
      $(".js-range-slider").on('change', function() {
        this.submitData()
    

    becomes

    mounted() {
      const instance = this;
      $(".js-range-slider").on('change', function() {
        instance.submitData()
    
    1. Store the this from mounted() into the event’s data by passing it in as the second argument to on():
    mounted() {
      $(".js-range-slider").on('change', function() {
        this.submitData()
    

    becomes

    mounted() {
      $(".js-range-slider").on('change', { component: this }, function(event) {
        event.data.component.submitData()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search