首页 文章

从组件外部调用Vue JS组件方法

提问于
浏览
109

假设我有一个包含子组件的主Vue实例 . 有没有办法完全从Vue实例外部调用属于这些组件之一的方法?

这是一个例子:

var vm = new Vue({
  el: '#app',
  components: {
    'my-component': { 
      template: '#my-template',
      data: function() {
        return {
          count: 1,
        };
      },
      methods: {
        increaseCount: function() {
          this.count++;
        }
      }
    },
  }
});

$('#external-button').click(function()
{
  vm['my-component'].increaseCount(); // This doesn't work
});
<script src="http://vuejs.org/js/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
  
  <my-component></my-component>
  <br>
  <button id="external-button">External Button</button>
</div>
  
<template id="my-template">
  <div style="border: 1px solid; padding: 5px;">
  <p>A counter: {{ count }}</p>
  <button @click="increaseCount">Internal Button</button>
    </div>
</template>

因此,当我单击内部按钮时, increaseCount() 方法绑定到其click事件,因此它被调用 . 没有办法将事件绑定到外部按钮,我用jQuery监听其click事件,所以我需要一些其他方法来调用 increaseCount .

EDIT

这似乎有效:

vm.$children[0].increaseCount();

但是,这不是一个好的解决方案,因为我通过子数组中的索引引用组件,并且对于许多组件,这不太可能保持不变并且代码可读性较差 .

6 回答

  • -1

    这是从其他组件访问组件方法的简单方法

    // This is external shared (reusable) component, so you can call its methods from other components
    
    export default {
       name: 'SharedBase',
       methods: {
          fetchLocalData: function(module, page){
              // .....fetches some data
              return { jsonData }
          }
       }
    }
    
    // This is your component where you can call SharedBased component's method(s)
    import SharedBase from '[your path to component]';
    var sections = [];
    
    export default {
       name: 'History',
       created: function(){
           this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
       }
    }
    
  • 150

    最后我选择使用Vue's ref directive . 这允许从父级引用组件以进行直接访问 .

    例如 .

    在我的父实例上注册了一个compnent:

    var vm = new Vue({
        el: '#app',
        components: { 'my-component': myComponent }
    });
    

    使用引用在template / html中渲染组件:

    <my-component ref="foo"></my-component>
    

    现在,在其他地方我可以从外部访问该组件

    <script>
    vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
    </script>
    

    看一下这个小提琴的例子:https://jsfiddle.net/xmqgnbu3/1/

    (使用Vue 1的旧示例:https://jsfiddle.net/6v7y6msr/

  • 20

    您可以使用Vue事件系统

    vm.$broadcast('event-name', args)
    

    vm.$on('event-name', function())
    

    这是小提琴:http://jsfiddle.net/hfalucas/wc1gg5v4/59/

  • 13

    假设您在子组件中有一个 child_method()

    export default {
        methods: {
            child_method () {
                console.log('I got clicked')
            }
        }
    }
    

    现在您要从父组件执行 child_method

    <template>
        <div>
            <button @click="exec">Execute child component</button>
            <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
        </div>
    </template>
    
    export default {
        methods: {
            exec () { //accessing the child component instance through $refs
                this.$refs.child.child_method() //execute the method belongs to the child component
            }
        }
    }
    

    如果要从子组件执行父组件方法:

    this.$parent.name_of_method()

    注意:建议不要像这样访问子组件和父组件 .

    相反,作为最佳实践,使用Props&Events进行亲子沟通 .

    如果你想要组件之间的通信肯定使用vuexevent bus

    请阅读这篇非常有帮助的article


  • 1

    由于Vue2适用于:

    var bus = new Vue()
    

    //在组件A的方法中

    bus.$emit('id-selected', 1)
    

    //在组件B的创建钩子中

    bus.$on('id-selected', function (id) {
    
      // ...
    })
    

    有关Vue文档,请参阅here . 并且here更详细地介绍了如何准确设置此事件总线 .

    如果您想了解何时使用属性,事件和/或集中式状态管理的更多信息,请参阅this article .

  • -2

    这是一个简单的

    this.$children[indexOfComponent].childsMethodName();
    

相关问题