Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: 'danger' }, it should turn red. Here is how I'm calling it:

 EventBus.$emit('call-modal', { type:'success' });

The challenge I'm facing is figuring out how to dynamically change the CSS of the modal based on the payload received through the eventBus. Can anyone help me achieve this functionality?

Below is a snippet of my sample component:

<template>
  <div>
   <button class="pleeease-click-me" @click="callModal()">Click me</button>
   <div class="modal" v-show="showModal">
     <h2>Message</h2>
   </div>
  </div>
</template>

<script>
import { EventBus } from '../App.vue';

export default {
  name: 'bankAccount',
  props: ['modalType'],
  data() {
    return {
      showModal: false
    }
  },
   methods: {
    callModal() {
      this.showModal = !this.showModal
      // Emitting an event with a payload when the button is clicked
      EventBus.$emit('call-modal', {type:'success'});
    }
  }
}

</script>

<style scoped>

.modal {
  height: 100px;
  width: 300px;
  border: solid gray 2px;
}
</style>

And here is a snippet of my App.vue component:

<template>
  <div id="app">

  <bankAccount/>
  </div>
</template>

<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue';
export const EventBus = new Vue();


EventBus.$on('call-modal', (type) => {

})

export default {
  data() {
   modalTypes = [
     { type: 'success' },
     { type: 'danger' },
   ]
  },
  name: 'app',
  components: {
    bankAccount
  },
}
</script>

<style>

</style>

Answer №1

Start by placing your modal component directly in the App.vue file. Define data properties like showModal and modalType within the component to store information about the modal. In the created hook, listen for call-modal events and update the data properties accordingly. Remember to apply the appropriate class based on the value of modalType. That's all it takes.

<template>
  <div id="app">
    <bankAccount />
    <div :class="['modal', `modal--type--${modalType}`]" v-show="showModal">
      <h2>Message</h2>
    </div>
  </div>
</template>

<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue'
export const EventBus = new Vue()

export default {
  name: 'app',
  components: {
    bankAccount,
  },
  data() {
    return {
      showModal: false,
      modalType: 'default',
    }
  },
  created() {
    EventBus.$on('call-modal', obj => {
      this.showModal = true
      this.modalType = obj.type
    })
  },
}
</script>

<style>
.modal {
  height: 100px;
  width: 300px;
  border: solid gray 2px;
}

.modal--type--success {
  border-color: green;
}
</style>

To trigger the modal, emit the 'call-modal' event using the EventBus.

EventBus.$emit('call-modal', { type: 'success' });

Answer №2

One essential step is to register and deregister the EventBus in your components.

This can be achieved either through using Vue.mixin for all components or by utilizing import in a single component:

<template>
  <div id="app">

  <bankAccount :class="modalTypes"/>
  </div>
</template>


<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue';
export const EventBus = new Vue();


EventBus.$on('call-modal', (type) => {

})

export default {
  data() {
   return {
     modalTypes = {
       'success': false,
       'danger': false
     }
   }
  },
  name: 'app',
  components: {
    bankAccount
  },
  created(){
    EventBus.$on('call-modal', this.callModal)
  },
  beforeDestroy(){
    EventBus.$off('call-modal', this.callModal)
  },
  methods: {
    callModal(evt){
      for(let key in this.modalTypes) 
        this.modalTypes[key] = key === evt.type
    }
  }
}
</script>

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

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

The functionality of changing the category in the second carousel slider on click using JavaScript appears to

Creating a bootstrap carousel slider that dynamically changes based on the selected category. For example, clicking on the hammer category will display only hammer images, while selecting the compass category will show compass images. Everything worked sm ...

What is the best way to seamlessly transition layers from one location to another as the mouse exits and re-enters the window?

I have been working on refining a parallax effect to achieve a seamless transition between two positions based on where the mouse exits and enters the window. In the JSFiddle example provided, there is a slight 'pop' that I am looking to replace ...

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...

I have added the same directive to both of my HTML files

Hello, I am facing an issue with a directive that I have included in two HTML files. The 'app' is set as ng-app. <dir auto=""></div> The code for the directive is as follows: app.directive("auto", function() { scope: { arr : ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

Having trouble making .click() function work in jQuery

Struggling with translating my javascript code to jQuery for homework. The .click function is causing me some serious issues. Here's a snippet of the code I'm working on: (document).ready(function() { $("start_test").click (function() { ...

Why is Handlebars {{body}} not rendering my HTML tags properly?

I am perplexed by the fact that the example in the other file is not showing. While working on a CRUD project with Mongo, Express, and Node, I encountered an issue. The code wasn't functioning as expected, so I paused to figure out why. <!DOCTYPE ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

Is it possible to hide the <dd> elements within a <dl> using knockout's custom data binding upon initialization?

I have implemented a <dl> where the <dd> can be expanded/collapsed by clicking on the corresponding <dt> using knockout's data binding. The inspiration for my solution came from a tutorial on creating custom bindings. Currently, I h ...

Sending a string array to MVC controllers through ajax

I've been struggling to pass a list of strings from a multiple select to the controller. Despite seeming like a simple requirement, I've spent hours trying to figure it out without success. I've done some research on this but haven't be ...

What could be causing the lack of change in direction for the initial function call?

There appears to be an issue with image(0) and image(1) in this array that I can't quite understand. The console output shows: i=5; div class="five" id="slides" i=0; div class="one" id="slides" i=1; div class= ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

Is it possible to integrate a Backbone app as a component within a separate app?

I am currently in the process of familiarizing myself with Backbone.js and front-end development, as my background is more focused on back-end development. I have a question related to composition. Imagine that I need to create a reusable component, like ...

Is it possible to postpone sending a message on Discord until a certain event has been successfully completed?

After the User leaves the Discord, I attempted to create a RichEmbed Message that would include a random GIF from Giphy. The GIF was meant to be generated using the getGiphyPic() function with the help of this node module: https://github.com/risan/giphy-ra ...