Pass along an event from a child component to its parent in Vue 2

As a newcomer to JS and Vue, I appreciate your patience with my learning curve :)

I've set up a table using two Vue components: a parent (representing the table - orders) and a child (representing the row - order).

Each row in the table has a button that triggers an AJAX call specific to that row. However, I also need the parent table to refresh after this action is completed in order to display updated data.

I believe I should utilize $emit in the child component to communicate the action to the parent, but for some reason, it's not working as expected. Here's the pertinent part of the code snippet:

const order = {
    template: `
        ...// table content
        <td><button class="btn btn-default btn-sm" @click="assignAdvisor(id, 
                                       selectedOption)">Set Advisor</button></td>
    `,

    methods: {
        // method triggered by the button click

        assignAdvisor(id, selectedOption) {
            axios.post('url').then(response => {
                ..// display response message
                orders.$emit('refreshAfterUpdate'); // attempted this.$parent.$emit(...) as well
            })      
    },   
};

const orders = {
    components: { order, },

    props: {
        orders: {
            type: Object,
        },
    },

    mounted() {
        var refresh = () => {
            axios.get('/admin/ajax/unassigned-orders')
                .then(response => {
                this.ordersData = response.data;
                setTimeout(refresh, 5000);
            });
        }
        refresh();
    },

    methods: {
        refreshAfterUpdate() {
            axios.get('/admin/ajax/unassigned-orders')
            .then(response => {
            this.ordersData = response.data;
            console.log(response);
            });
        },
    }
};

new Vue({
    render(createElement) {
        const props = {
            orders: {
                type: Object,
            },
        };
        return createElement(orders, { props });
    },
}).$mount('#unassignedOrders');

Despite no error messages being displayed, the functionality doesn't seem to be working correctly.

Appreciate any insight or guidance. Thank you!

Answer №1

Thanks to the guidance of @Patrick Steele, I finally cracked the code.

I made the mistake of not utilizing $on - my bad.

By including the code in the mounted() section, everything fell into place:

const order = {
    template: `
        ...// table content
        <td><button class="btn btn-default btn-sm" @click="assignAdvisor(id, 
                                       selectedOption)">Set Advisor</button></td>
    `,

    methods: {
        // this method executes when the button is clicked

        assignAdvisor(id, selectedOption) {
            axios.post('url').then(response => {
                ..// display response message
                orders.$emit('refreshAfterUpdate'); // also tried  
                                                   // this.$parent.$emit(...)
            })      
    },   
};

const orders = {
    components: { order, },

    props: {
        orders: {
            type: Object,
        },
    },

    mounted() {
        // below is the code that needs to rerun on button press,  
        // shown again in a method
        var refresh = () => {
            axios.get('/admin/ajax/unassigned-orders')
                .then(response => {
                this.ordersData = response.data;
                setTimeout(refresh, 5000);
            });
        }
        refresh();

            $this.on('refreshAfterUpdate', () => {
                axios.get('/admin/ajax/unassigned-orders')
                .then(response => {
                this.ordersData = response.data;
                console.log(response);
                });
            },
        },
    },


};

new Vue({
    render(createElement) {
        const props = {
            orders: {
                type: Object,
            },
        };
        return createElement(orders, { props });
    },
}).$mount('#unassignedOrders');

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

Guide on extracting unique identifiers from an array of objects and sorting them by the earliest date in JavaScript

I've got an array of objects and I'm looking to retrieve the items with unique IDs while also selecting the earliest date. For example: [{id:1, date: Jan 12}, {id:2, date: Feb 8}, {id:3, date: Feb 8}] var array = [{id: 1, date: Jan 12 2021 08:00 ...

Exploring the hover functionality in GetOrgChart

Exploring mouse hover functionality in Getorgchart view. Looking to implement the mouse hover and mouse out events in Getorgchart view. Can I access the org chart element details during mouse hover/leave actions? ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

Retrieve the visible text content of an element by utilizing various ids

I am currently working on a project using AngularJS with multiple conditions all sharing the same id. My goal is to extract text only from the condition that evaluates to true. Recently, I discovered a major bug in an app that I am preparing for release. ...

Utilizing ProtractorJS to Extract Numbers from Text within an Element and Dynamically Adding it to an Xpath Expression

Situation My objective is to extract text from an element on a webpage, convert that extracted text into a number in string format, and then use it for an xpath query. The code snippet below illustrates this process: var bookingRefString = element(by.css ...

I am currently working on a Node.js application generated with express-generator and am experimenting with integrating Primus websocket

Currently in the process of developing a nodejs app using express-generator. I'm facing an issue while trying to integrate the Primus websocket into my application. The issue arises when I do not include app.listen(port) in my app.js file, causing the ...

Class does not have the capability to deserialize an array

I encountered this issue with my code (see image): https://i.sstatic.net/QxI0f.png Here is the snippet of my code: function CheckLoginData() { var user = []; user.Email = $("#tbEmail").val(); user.Password = $("#tbPassword").val(); $.ajax({ type ...

Exploring the options for accepting various file formats with Swal SweetAlert

Currently, I am using Swal Sweet Alert within my Vue.js application. I have successfully implemented code to allow image files, but now I am seeking assistance on how to extend this functionality to include multiple file types such as PDFs, PPTs, and Doc ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Tips for resizing images from Amazon S3 using Sharp

I'm encountering an issue while attempting to resize an uploaded image from S3 using @aws-sdk/v3 in a Node.js API. Initially, I retrieve the object (image) from S3 by following this example: https://github.com/awsdocs/aws-doc-sdk-examples/blob/master ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

What is the best way to utilize external, customizable scripts within Nuxt.js?

I'm in the process of developing a Nuxt website and I need to be able to edit a specific JavaScript file after building in order to update the content of a table. Does anyone have any suggestions on how I can achieve this? So far, my attempts to incl ...

Instructions on converting text to a Float value and displaying the calculated result in a separate div

I am attempting to extract a string from a div, clear its content, then retrieve the actual price from ".skuBestPrice", remove any special characters, perform calculations to convert it into a floating point number, and display this number in the div ".tot ...

Performing an Ajax request upon the completion of page loading

I am currently working on creating a search functionality for a page, where users can input text into a search box and the page will display results based on their search. However, I am facing some timing issues as the blank search page is loading before ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

Issue encountered: The method written in the Vue modal template is not defined in Laravel

Currently, I am handling the CRUD functionality in a Laravel application. The requirement is that when the delete button associated with an entry is clicked, a modal should appear prompting the user to confirm the deletion of that particular entry. I att ...

Retrieve information from an ajax call within an Angular application

I need assistance with 2 requests I have. $.ajax({ type: "POST", url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token", data: "grant_type=client_credentials", headers: { 'Content-Type': 'application/x-www-form-urlencoded&a ...

What is the best way to incorporate multiple variables in a MySQL query when using Node.js?

I'm facing a challenge where I need to input student data into a table using the parent key as a foreign key. The parent information is included in the same JSON object, with an array of students inside it. My goal is to retrieve the parent Id from th ...