Ways to retrieve information from a component using a function

Hello! I'm currently facing a challenge with the following scenario:

I am developing a Vue application with multiple components. One of these components utilizes vee-validate for validation purposes. I need to modify a data element within the component's data() object for custom validation. However, when attempting this, I encounter the error message: cannot set property 'kenteken' of undefined.

The code snippet in question is as follows:

<script>
    import {Validator} from 'vee-validate';
    import nl from 'vee-validate/dist/locale/nl';

    const isKenteken = (value) =>{
        app.loader.kenteken= true;
        return axios.post('/api/validate/kenteken', {kenteken: value}).then((response) => {
            // Returning an object with valid and data properties
            app.loader.kenteken = false;
            app.voertuig.merk = response.data.Algemeen.Merk;
            app.voertuig.model = response.data.Algemeen.Type;
            app.voertuig.brandstof = response.data.Algemeen.Brandstof.toLowerCase();
            app.voertuig.type_id = response.data.Algemeen.TypeId;
            app.voertuig.model_id = response.data.Algemeen.ModelId;
            app.voertuig.merk_id = response.data.Algemeen.MerkId;
            console.log(response.data.Algemeen);
            return {
                valid: true,
                data: {
                    message: response.data.Algemeen,
                }
            };
        }, (error) => {
            console.log(error);
            app.voertuig.kenteken = '';
            app.loader.kenteken_onbekend = 1;
            app.loader.kenteken = false;
            return false;

        });
    };

    Validator.localize('nl', nl);

    Validator.extend('kenteken', {
        validate:isKenteken,
        getMessage: (field, params, data) => {
            loader.kenteken = false;
            voertuig.merk = data.message.Merk;
        }
    });

    export default {
        name: "app",
        data() {
            return {
                voertuig: {
                    kenteken: '',
                    model: '',
                    model_id: '',
                    type: '',
                    type_id: '',
                    merk: '',
                    merk_id: '',
                    brandstof: '',
                    schadevrijejaren: ''
                },
                bestuurder: {
                    geboortedatum: '',
                    postcode: '',
                    huisnummer: '',
                    straat: '',
                    woonplaats: ''
                },
                loader: {
                    kenteken_onbekend: false,
                    kenteken: false,
                },
            }
        },
        mounted() {
            var self = this;
        }
    }
</script>

How can I access the load.kenteken within the isKenteken function?

Answer №1

Avoid creating functions that reference Vue components outside of the Vue application scope. It is recommended to place the isKenteken() function within the Vue component as shown below:

<script>
    import {Validator} from 'vee-validate';
    import nl from 'vee-validate/dist/locale/nl';

    Validator.localize('nl', nl);

    Validator.extend('kenteken', {
        validate:isKenteken,
        getMessage: (field, params, data) => {
            loader.kenteken = false;
            voertuig.merk = data.message.Merk;
        }
    });

    export default {
        name: "app",
        data() {
            return {
                // Data properties here
            }
        },
        methods{
          // Methods here
        },
        mounted() {
            var self = this;
        }
    }
</script>

If you need to access the function from another component, ensure they are referencing this component correctly. For instance, inside the other component's mounted(), utilize the root component's methods with this.$root.isKenteken()

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

Is this loader going through a triple loop?

<style> .loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background-repeat: no-repeat; background: url('images/page-loader.gif'); } </style> <script src="//ajax.googleapis.com/ajax/libs/jque ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Heroku is experiencing issues with loading Firebase credentials

Difficulty with Firebase Integration on Heroku Currently, I am facing an issue with my Node.js server deployed on Heroku that interacts with Firebase. When attempting to run the application on Heroku, I encounter an error stating that it is unable to load ...

Sending multipart/form-data with ajax in PHP returns as null

Recently, I encountered an issue with a form I have. It has the following attributes: method="post" and enctype="multipart/form-data" Every time I submit the form using AJAX $("#openTicketSubmit").click(function(){ var support_ticket_form_data = new ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

What is the best way to combine HTML and JavaScript code within a single JavaScript file?

Is there a way to include a responsive iframe without any scroll in multiple websites by using just one line of code? I found this snippet that seems promising: <script src="testfile.js"></script> The testfile.js contains the necessary HTML a ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

Using a JSP page to trigger a JavaScript function

I am attempting to execute an in-page JavaScript function from within a JSP page. Here is the code snippet, however, the JavaScript functions do not appear to be executing when the JSP page loads on the client side. Is there anything incorrect with the a ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Tips for creating a dynamic menu with animated effects

Check out my fiddle here: http://jsfiddle.net/k3AHM/23/ $(document).scroll(function () { var y = $(this).scrollTop(); if (y > 110) { $('.menu-container').addClass( "fix-menu" ).animate('top', '-3px&a ...

What is the best way to track and document the specific Context Provider being utilized while invoking useContext?

After creating a custom component that displays AuthContext.Provider with specific values, I encountered an issue. Even though it functions correctly, when I utilize useContext within a child of the AuthProvider component, my code editor (VS Code) is unabl ...

Guide to authenticating users using Vue JS and Django

Currently, I am collaborating on a compact university venture utilizing Vue JS, Django2, and Django Rest Framework. The project involves two distinct user roles with varying actions within the application. The aspect that is leaving me puzzled is the logi ...

Javascript/Jquery - Eliminating line breaks when transferring text to a textarea by copying and pasting

Is there a method to paste text into a textarea that will automatically remove any line breaks or whitespaces? For instance, if I copy the following text and paste it into the textarea: abcdef, ghijkl, mnopqrs I would like it to appear in the textarea as ...

Discover how to fetch data within Vue component using data access object in Vue 3

I am in the process of utilizing a data access object (dao) named Todos.js to fetch necessary data for a Vue3 component called List.vue. Below, you will find snippets from my code as an example. Upon initializing the application, the data is successfully ...

Setting a custom expiration time for a custom token in Firebase authentication

Using the firebase custom auth, I have created a custom token. I am looking for a way to customize and update this token by shortening its expiry time based on when a session finishes. For example, if a session ends after 20 seconds or 5 minutes, I want to ...

`The console is displaying incorrect results when returning a JSON object`

Need to extract the full address as well as the lat and long values from the provided JSON data. var place = { "address_components": [{ "long_name": "17", "short_name": "17", "types": [ "street_number" ] }, ... ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

Connecting event listeners to offspring elements, the main element, and the entire document

My request is as follows: I have multiple boxes displayed on a webpage, each containing clickable divs and text. When a user clicks on a clickable div, an alert should appear confirming the click. Clicking on the text itself should not trigger any action. ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

What is the best way to create clickable <tr> elements that function as links rather than cells?

Although it seems simple, I am struggling to achieve this task. I have a list of rows with 6 columns that display data from MySQL. I want to make each row clickable instead of just a cell, which will open a new URL in a new tab. Below is the structure I ...