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

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

What is the maximum duration we can set for the Ajax timeout?

I am facing a situation where an ajax request can take between 5-10 minutes to process on the server side. Instead of continuously polling from JavaScript to check if the request is completed, I am considering making just one ajax call and setting the tim ...

Bringing in PeerJs to the NextJs framework

Currently delving into NextJs and working on creating an audio chat application, I've hit a roadblock while attempting to import PeerJs. An error message keeps popping up saying 'window is not defined'. import Peer from 'peerjs'; ...

Issue: Module 'C:viteinvite.js' not found while setting up vue.js in Laravel project

Decided to dive into learning Laravel and Vue.js, so I followed a tutorial for installation found here: https://youtu.be/WLQDpY7lOLg?t=1058 Everything was going smoothly until I reached the npm run dev command... Below are the commands I executed in the ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

The Firebase Authentication JS library does not properly fill the `providerData` array

Within my VueJS / QuasarJS application, I am utilizing firebase-js-sdk [1] in conjunction with firebaseui-web [2] to manage authentication processes. After a successful authentication using any of the configured providers (such as password, google, apple, ...

What is the best way to ensure that a child div can expand to fit within the scrollable area of its parent div

I am facing an issue with a parent div that changes size based on the content inside it. When the content exceeds the initial size, causing the parent to scroll instead of expanding, I have a child div set to 100% width and height of the parent. However, t ...

Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to preve ...

Building a framework for combined frontend and backend plugins using Vue and Express

Currently, I am facing a challenge with my repository which contains a Vue CLI-generated frontend application and an Express backend application. The setup involves a standard Vue CLI app with a top-level backend src folder. The Express app defines various ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

Instructions on how to determine if a client is a "desktop terminal"

So here's the deal: I have a suspicion about thin clients accessing my website. Is there a way to test if a client is a thin client without causing it to lag with JavaScript animations? I want to provide a simplified version of the site for these clie ...

Using Vue 3 to dynamically render a component from a string

I have a question about the ValidateCheckboxes component I am working with. ValidateCheckboxes is a specialized list of checkboxes that I pass to the component as props. Here's how it typically looks: view image here view image here I use v-for to dis ...

Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call handleProducts() function handleProducts() { var display = document.getElementById("display") var url = "http://127.0.0.1:800 ...

React State not refreshing

Currently tackling a challenging e-commerce project and facing an obstacle with the following component: import React, { useEffect, useState } from 'react'; const Cart = () => { let [carts, setCarts] = useState([]); let [price, se ...

Guide on resolving the error "Type 'Emits' does not have any call signatures" in Vue 3 with the combination of script setup and TypeScript

I've come across some code that seems to be functioning properly, but my IDE is flagging it with the following warnings: TS2349: This expression is not callable. Type 'Emits' has no call signatures Below is the code snippet in question: ...

Is it possible to create a component with a button that triggers the rendering of a different component?

I am struggling to implement an 'edit' button within a component that, upon clicking, should display a separate component known as a 'client edit modal'. I'm facing challenges in figuring out how to achieve this functionality. The ...

What are the steps to ensure availability validation with jQuery validation?

I need assistance with validating post availability in the database using jQuery validation functionality. I have already implemented validation using the code below, but I am unsure where to place an Ajax validation before submitting the form. $(document ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

Authentication using tokens - JSON Web Tokens

While working with jsonwebtoken in Node, we generate a unique token for each user and return it to them. But when the user sends this token in the authentication header (Authentication: <token>), how does jwt differentiate between tokens from diffe ...