Parent-Child Communication in VueJS 2.0: How to effectively pass data from the parent component

Does anyone know a straightforward solution to this issue? I've been struggling to find one.

Within my HTML file, there's a button that looks like this:

<button @click="showModal">Show Modal</button>

By clicking on the button, it triggers the following method:

new Vue({
    el: '#root',
    methods: {
        showModal() { Event.$emit('showModal'); },
    }
});

My goal is to toggle a class in a modal component when the button is clicked. Below is part of the component's code relevant to this functionality:

Vue.component('modal', {

    template: `
        <div :class="[ modalClass, {'is-active' : isActive }]">
            ETC...
        </div>
        `

    data() {
        return {
            isActive: false,
            modalClass: 'modal'
        }
    }

Being new to VueJS, I'm finding it challenging to communicate effectively within Vue. What steps should I take to ensure that isActive becomes true upon clicking the button?

Your input and advice would be greatly appreciated!

Sincerely,

Moshe

Answer №1

If you're working in your main.js file (or wherever you initialize your Vue app)

You have the option to utilize a basic vue instance as an eventbus

Vue.prototype.bus = new Vue();

This allows you to use it like this:

this.bus.$on('event', (params) => {})

this.bus.$emit('event', params)

Take a look at one of my vue projects on GitHub for reference, I use the eventbus extensively. https://github.com/wilomgfx/vue-weather

Also, don't miss out on this fantastic free series on VueJS 2, it's really helpful :

Here's a complete example using the original poster's question:

https://codepen.io/wilomgfx/pen/OpEVpz?editors=1010

Answer №2

When it comes to communicating from a parent component to a child component in Vue.js, you can utilize component props.

If the communication needs to go even deeper, where the parent communicates with a nested child component, you can make use of the busEvent method as suggested by @WilomGfx.

Here is an example code snippet for communication from parent to child:

Vue.component('modal', {
        template: '<div :class="[ modalClass, {\'is-active\' : isActive }]">' +
            'Hello Word !' +
        '</div>',
        data() {
            return {
                modalClass: 'modal'
            }
        },
        props: {
            isActive: { type: Boolean, default: false }
        }
    });

    new Vue({
        el: '#root',
        data() {
          return {
            isActive: false,
          }
      },
      methods: {
        showModal() {this.isActive = true },
      }
    });
.is-active {
      color: red;
    }
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="root">
  <modal :is-active="isActive"></modal>
  <button @click="showModal">Show Modal (going red when prop isActive is true)</button>
</div>

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

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

The CORS policy is preventing the AJAX request from functioning properly on localhost

Recently, I have been working on an Angular application that requires interaction with an API. To test it out, I set up an API on my localhost and made a request using AJAX. However, I encountered the dreaded CORS error. Despite trying various solutions fo ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

I am encountering an issue where body-parser is not functioning properly with typescript. Whenever I make a request, the request.body is returning as undefined

Below is the code snippet for my Express application using TypeScript version 3.7.4: import bodyParser from "body-parser"; import config from "config"; import cookieParser from "cookie-parser"; import express from "express"; import mongoose from "mongoose ...

Is node.js required for utilizing Angularjs?

Considering incorporating angular.js into my website's Image Editing Tool. Is node.js necessary for this integration? I'm a bit puzzled here. Are there instances where both nodejs and angularjs are used together, or can they operate independentl ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...

Avoid using the JavaScript 'Sys.WebForms..' function if there is no ScriptManager present on the page

Currently, I am using a single JavaScript binding in the Master Page for my entire project. However, the Master Page does not include a ScriptManager. This means that some pages have Ajax components, such as UpdatePanel, while others do not. The 'Sys. ...

angular interpolation:issue arises when inserting URL stored in a variable

A challenge I'm facing involves adding a dynamic id to a YouTube URL, which looks something like this: <iframe width="460px" height="415px" ng-src="{{post.youtube_id}}" frameborder="0" allowfullscreen></iframe> One of the URLs I'm a ...

Is Redux really the new trend in the world of action creators?

I am new to this. I'm a bit unsure, is it okay or silly to use the pattern below? import { createAction, handleActions } from "redux-actions"; const CHANGE_STATE = "appState/CHANGE_STATE"; export const changeState = createAction(CHANGE_STATE, (key, ...

How can I trace the origin of a post request sent from a form?

When constructing an HTML form, I typically utilize <form action="/postRoute" method="post"> to submit a post request. However, while examining a form for which I needed the post request URL, I came across the following: <form action="index.cf ...

What is the best way to implement restful instead of query syntax in a $resource factory?

Recently, I set up a $resource factory like this: (function() { 'use strict'; app.factory('WidgetFactory', [ '$resource', function($resource) { return $resource('http://localhost:8282/widget/:widgetId&apo ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Is the Bootstrap Carousel not automatically scrolling when navigating back in Angular?

Whenever I launch my Angular application, the image slider implemented using Bootstrap carousel functions properly. However, upon navigating to another view and returning to the image slider, it no longer auto-slides. Even though I can manually navigate th ...

Webpack referencing incorrect node_modules directory

I am currently working on a Vue client project that incorporates a Vue library project. The Vue library project also utilizes some third-party packages such as vue-material. These two projects are connected through the client project's Package.json f ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

A distinct handler function designed for a dynamically generated form

I have 3 MaterialUI TextFields that are rendered n number of times based on user input (stored in a variable named groupMembersCount) in a functional ReactJS component using the useState hook: const [groupDetails, setGroupDetails] = React.useState([ { ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...