简体   繁体   English

如何使用vuejs2从另一个组件执行功能

[英]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. 这是一个示例:单击elemnt,然后打开侧边栏,mysiderbar调用一个函数,该函数将调用警报功能。

But my code is been executes from my mounted function form vuejs 但是我的代码是从安装的函数形式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? 我要在侧边栏打开时调用功能警报吗?

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 https://codepen.io/senta/pen/NpZVxg?editors=0010

In the first file Server Status I $emit a event in vuejs 在第一个文件“服务器状态”中,我在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. 从第二个文件中,我得到一个名为this。$ on('some-event')的事件,该事件称为我的函数callAlert(),然后触发给定的函数并显示警报。

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

try to register a global reference (Maybe not the best alternative) to your function. 尝试为您的函数注册一个全局引用(也许不是最好的选择)。

Your second file: 您的第二个文件:

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

In your first file: 在您的第一个文件中:

mounted () {
    this.$alert()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM