Search code examples
javascriptvue.jsvuejs2vue-directives

How to execute a function from another component using vuejs2


I have a component thats need to colling a event when my sidebar opens and I need to call this function every time that I need to open my sidebar.

Here is a example: I click in a elemnt the elemnt open my sidebar and mysiderbar calls a function that will calling a alert function.

But my code is been executes from my mounted function form vuejs

Here is my first file that will call 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>

Here 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>

I want to call a function alert when the sidebar opens?


Solution

  • So, I found a solution to my problem and I know that probably exist a better way to do, but works for me. unfortunately I didn't found any specific tutorial to do this, but this sample helped me a lot.

    https://codepen.io/senta/pen/NpZVxg?editors=0010

    In the first file Server Status I $emit a event in vuejs

        <template>
            <div>
                <p>Just a template</p>
                <div id="storage">ITs ME</div>
            </div> </template>
    
        <script> export default {   name: 'home',   methods: {
              //https://codepen.io/senta/pen/NpZVxg?editors=0010
              //chamar a função extena
              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>
    

    And from the second file I get the event this.$on('some-event') that's call my function callAlert() then the given function is triggered and shows the alert.

    <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>
    

    Thanks