Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component.

When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. This function then calls a composable function.

const getCall = async (param_search) => {
        let response = await axios.get('/api/callApi', {param_search: {'param_search': param_search} }) 
        console.log(response.data.data)
        calls.value = response.data.data
    }

My problem is that I don't know how to call this function. In my parent component, I have:

<input type="button" class="btn btn-dark" value="Search Records" @click="searchRegisters()">

const nAsignedCalls = ref(null);
function searchRegisters(){
                var address = "";
                var city = "";
                var cp = "";

                address = document.getElementById("address").value
                if( address != "" ) {
                    param_search = "address";
                }

                city = document.getElementById("city").value
                if( city != "" ) {
                    param_search = "city";
                }

                cp = document.getElementById("postal_code").value
                if( cp != "" ) {
                    param_search = "cp";
                }

                nAsignedCalls.getCalls(param_search);
            }

In my destination component:

return {
   ...
   getCalls
}

But when I click the button, I get the following error in the console:

nAsignedCalls.getCalls is not a function
    at Proxy.searchRegisters (app.js:20068:21)
    at onClick._cache.<computed>._cache.<computed> (app.js:21727:19)
    at callWithErrorHandling (app.js:7336:22)
    at callWithAsyncErrorHandling (app.js:7345:21)
    at HTMLInputElement.invoker (app.js:15616:86)

Update:

Here is my composable code:

export default function useNcalls(){
    let calls = ref([])
    let param_search = ref([])
    let pagination = ref([])

    const getCall = async (param_search) => {
        let response = await axios.get('/api/callApi', {param_search: {'param_search': param_search} }) 
        console.log(response.data.data)
        calls.value = response.data.data
    } 
    const deleteCall = (id) => axios.post(`/api/callApi/${id}`, {_method: 'delete'}).then(res => {
        confirm("Are you sure you want to delete the record?"); 
        location.reload();
    }).catch(err => {
        console.log(err);
    });  
    
    const queryForKeywords = async (event) => {
        const response = await axios.get('/api/callApi/show', { params: { 'searchParams': event } }) 
        calls.value = response.data.data
    };

    const getResults = async (page) => {
        const response = axios.get('api/callApi?page=' + page)
        calls.value = response.data
    };

    const getItems = async (page) => {
        axios.get('/api/callApi?page='+page)
            .then(response => {
                calls.value = response.data.data;
                pagination.value = response.data.meta;
            });
    };

    expose({ getCalls })

    return{
        calls,
        getCall,
        deleteCall,
        queryForKeywords,
        getResults,
        getItems
    } 
}

What am I doing wrong? Thank you for reading and sorry for my poor English.

Answer №1

When creating a setup() function, remember that it only allows a component's properties to be accessed within its own template. If you want to make these properties available to a parent component, you will need to utilize the expose method

export default {
  setup(props, { expose }) {
    const getCalls = () => { ... }

    expose({ getCalls })
  }
}

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

What could be causing the API link to not update properly when using Angular binding within the ngOnInit method?

Hi there, I'm currently working on binding some data using onclick events. I am able to confirm that the data binding is functioning properly as I have included interpolation in the HTML to display the updated value. However, my challenge lies in upd ...

Show a string on different lines

I'm looking to format my string so that it displays on multiple lines. I attempted to use replaceAll(",", "\n"), but it didn't work as expected. Here's the code snippet: <template> <v-form> <v-container> ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

An issue arises in Node.js and MongoDB where data is being returned from the previous update instead of the most

Currently, I'm delving into the world of Node.js and creating a platform where individuals can vote on different items and view the results afterward. The voting process involves utilizing the /coffeeorwater POST route, which then redirects to the /re ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

"Firebase offers the flexibility to have several 'apps' configured, both on the client side and the server

Currently, I have a firebase app set up in my project for SSR using firebase-admin. However, I now want to add firebase@8 to be able to utilize it on the client-side and eventually apply firestore rules. The issue arises when I try to use firebase@8, I enc ...

Employing the 'this' keyword for iterating over a jQuery selector

Having an issue with a jQuery code that logs the values of input fields on button click: Tried using forEach method on inputs but getting an error saying it's not a function. Why is this happening? $("#submit").click(e => { e.preventDefault(); ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

Unique syntax using markdown-react

I want to customize the syntax highlighting in react-markdown. Specifically, I would like to change the color of text inside {{ }} to blue while still maintaining the correct formatting for other elements, such as ## Header {{ }} import React from " ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Obtain the breakpoint value from Bootstrap 5

We have recently updated our project from Bootstrap 4 to Bootstrap 5. I am trying to retrieve the value of a breakpoint in my TypeScript/JavaScript code, which used to work in Bootstrap 4 with: window .getComputedStyle(document.documentElement) .g ...

Tips for creating Selenium code to verify the asterisk symbol

Looking to create Selenium code for validating the presence of asterisks with mandatory fields such as First Name*, Last Name*, Enter Address*, and Enter Phone Number*. The validation needs to confirm the asterisk appears after each field name. Currently ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Optimizing Google e2e testing using Protractor

Improving login efficiency is necessary to enhance the speed of executing e2e tests. At present, after every test, the Chrome browser shuts down, requiring a new login session for each subsequent test. What changes can be made to address this issue? Any ...

How to update newly added information through the existing form in ReactJS

Currently, I am working on a CRUD operation in my project. So far, I have successfully implemented the functionalities to add, delete, and display data. However, I am facing challenges with updating existing data. Despite trying various methods, none of th ...

Having difficulty specifying numerical entries only

I have been attempting to create an input field that only accepts numbers, but for some reason it still allows letters to be entered. Why is this happening? <input type="number" pattern="[0-9]" ...

Avoid changing the regex pattern if it is surrounded by a specific character

I want to change all occurrences of strings enclosed by - with strings enclosed by ~, unless the string is again surrounded by *. For instance, consider this string... The -quick- *brown -f-ox* jumps. ...should be altered to... The ~quick~ *brown -f-ox ...

how do I modify my JavaScript code to achieve the desired outcome

How can I program a button to disable after being pressed 10 times in less than a minute, but continue counting if not pressed for 1 minute? function buttonClicked() { if (totalCount + accCounter > 9) { document.getElementById("btn").disabled = ...