A guide on calling a function from a different component in vuejs2

I am facing a situation where I need to trigger an event whenever my sidebar opens. This event should be called every time the sidebar is opened.

For example, when I click on an element, it triggers the opening of my sidebar which then calls a function that displays an alert.

The issue I am encountering is that my code is being executed from the mounted function in Vue.js

Below is my first file that initiates the call to my side bar:

<template>
    <div>
        <p>Just a template</p>
    </div>
</template>

<script>
export default {
  name: 'home',
  data: function() {
      return {
          status: 'critical'
      }
  },
    mounted() {

        var openSidebar = function() {
            document.getElementsByClassName('side-bar')[0].style.display = 'block';
        };
        document.getElementById('box').addEventListener('click', openSidebar);
    },

}
</script>
<style>

</style>

This is my second file:

<template>
   <div>
     <app-server-status></app-server-status>
     <div id="box">
       <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique laborum repellat nihil maxime et veniam sed, sequi minima, quasi ipsum enim.</p>
     </div>
     <div class="side-bar">Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro amet sed autem non qui dolor minima. Incidunt eos recusandae doloribus hic nesciunt nostrum suscipit dolorum velit, voluptatum, accusamus, ullam fugiat!</div>
   </div>
</template>

<script>
//import local component server status
import ServerStatus from './ServerStatus.vue';

export default {
  name: 'home',
  components: {
      'app-server-status': ServerStatus
  },
  methods: {
        callAlert() {
                alert('TESTE')
            }
        },
  created() {
  },
  mounted() {
    function callAlert() {
      alert('Test');
    }

  },
}
</script>
<style>
  #box {
    background: red;
    width: 200px;
    height: auto;
    float: left;
  }
  .side-bar {
    position: absolute;
    width: 250px;
    height: 400px;
    right: 0;
    display: none;
    background: blue;
  }

</style>

How can I successfully call an alert function when the sidebar opens?

Answer №1

After much searching, I finally stumbled upon a solution to my problem that works well for me, even though there may be more efficient methods out there. I couldn't find a specific tutorial on this issue, but a helpful sample guided me in the right direction.

Link to CodePen Sample

The first file, Server Status, involves emitting an event in Vue.js using $emit.

<template>
    <div>
        <p>Just a template</p>
        <div id="storage">ITs ME</div>
    </div> </template>

<script> export default {   name: 'home',   methods: {
      //Invoke an external function
      openSidebar: function () {
        var vm = this;
        document.getElementById('box').addEventListener('click', function () {
            vm.$parent.$emit('some-event');
            var elem = document.getElementsByClassName('side-bar')[0].style.display;

            if(elem === 'none' ) {
                document.getElementsByClassName('side-bar')[0].style.display = 'block'
            } else {
                document.getElementsByClassName('side-bar')[0].style.display = 'none'
            }
        });
      },   },
    mounted() {
        this.openSidebar();
    },  
} 
</script> 
<style>
    #storage {
        background: rebeccapurple;
        color: white;
        padding: 10px 10px;
        margin-bottom: 20px;
    } </style>

In the second file, I listen for the event with this.$on('some-event') and call the function callAlert() to trigger an alert message.

<template>
   <div>
     <app-server-status></app-server-status>
     <div id="box">
       <p>IAM A TOOGLE</p>
     </div>
     <div class="side-bar" style="display: none;" >Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro amet sed autem non qui dolor minima. Incidunt eos recusandae doloribus hic nesciunt nostrum suscipit dolorum velit, voluptatum, accusamus, ullam fugiat!</div>
   </div>
</template>

<script>
//import local component server status
import ServerStatus from './ServerStatus.vue';

export default {
  name: 'home',
  components: {
      'app-server-status': ServerStatus
  },
  methods: {
        callAlert() {
          var elem = document.querySelector('.side-bar');
          var elemC = elem.style.display;
          if (elemC !== 'block') {
              alert('Opening');
            } else {
              alert('Close');
            }
          }
        },
     created: function () {
      this.$on('some-event', () => {
      this.callAlert();
    })
  },
  mounted() {
  }
}
</script>
<style>
  #box {
    background: red;
    width: 200px;
    height: auto;
    float: left;
  }
  .side-bar {
    position: absolute;
    width: 250px;
    height: 400px;
    right: 0;
    background: blue;
  }

</style>

Appreciate any help!

Answer №2

One approach could be creating a global reference to your function (although it may not be the most ideal solution).

In the second file, you can do the following:

...
 methods: {
     callAlert: function() {
      alert('test');
     }
 }
 mounted () {
    this.$alert = this.callAlert
 }
...

And in your first file:

mounted () {
    this.$alert()
}

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 Implementing Right-to-Left (RTL) Support in Material UI React

Currently, I am in the process of developing an application designed for LTR usage, but I am interested in adding RTL support as well. The application itself is built on top of Material UI React. By using CSS Flex Box, I have managed to rotate the applicat ...

Ensuring Data Integrity with JavaScript Form Validation

Ensure that if text box A is filled in, text box B must also be filled in before submitting. Vice versa, if text box B is filled in, make sure text box A has data as well. Is it possible to loop this check for multiple text boxes? For example, if row A o ...

Ways to trigger javascript following each ajax or complete request

I have a jQuery function that attaches a click event to specific elements, as shown below. $(".alert-message .close").click(function(e) { $(this).parent().fadeTo(200, 0, function() { $(this).slideUp(300); }); e.preventDefault(); }) ...

Tampermonkey feature: Extract source code with a button click from a constantly updating AJAX page

My goal is to create a simple script that can copy the source code of a dynamic AJAX page whenever I press a button. The current code, which I have included below, seems to be working fine: // ==UserScript== // @require http://ajax.googleapis.com/ajax/li ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Can jQuery Autocomplete function without stopping at white spaces?

Is there a way to modify jQuery UI autocomplete so that it can handle multiple words instead of terminating with a space? For example, if you input "New York City", it should still filter results based on each word. $.ajax({ type: "GET" ...

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

What is the best way to clear the states of a Nuxt app when logging out?

After a user logs out of the app, the Pinia persistent authStore state is reset and they are redirected to /login. However, if another user logs in without refreshing the page, the main page may still display the previous user's data because it remain ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Transmitting HTTP headers using Node.js

Within my Node JS Express application, I have an API endpoint called 'download' that returns a buffer to the calling application along with a header named 'status', which is a Javascript object. The response from Node sends the buffer ...

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...

When using JQuery's :first selector, it actually chooses the second element instead of the first

I'm facing an issue with a JQuery script that makes an AJAX request to the following URL https://djjohal.video/video/671/index.html#gsc.tab=0, which holds information about a video song. My goal is to extract and retrieve all the details from the HTM ...

Implementing conditional styling in Vue.js using v-bind based on specific Bootstrap breakpoints

Is there a way to dynamically assign styles based on different bootstrap breakpoints using v-bind style directive with vue? I'm encountering an error in the console that says "Whitespace was expected." <div class="footer" :style="{$b ...

How can you gradually fade out the bottom edge of a rendered component until it is re-rendered?

Currently, I am developing a reviews microservice for an e-commerce platform using react and react-bootstrap. My goal is to showcase 5 reviews initially, followed by a button to expand and reveal more reviews. In order to achieve this, I envision the botto ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

Building a listview using Angular, MySQL, and Node.js

As a newcomer to Angular, I've been navigating my way through the learning process with some success but also encountering challenges. Although I've managed to resolve certain issues within the application, such as successfully inserting data int ...