【问题标题】:Call a Vue.js component method from outside the component从组件外部调用 Vue.js 组件方法
【发布时间】:2018-03-13 21:32:26
【问题描述】:

假设我有一个包含子组件的主 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() 方法被绑定到它的点击事件,所以它被调用。无法将事件绑定到外部按钮,我正在使用 jQuery 监听其单击事件,因此我需要其他方式来调用 increaseCount

编辑

这似乎可行:

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

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

【问题讨论】:

  • 如果您想尝试一下,我使用 mxins 添加了一个答案。在我看来,我更喜欢以这种方式设置应用程序。

标签: javascript vue.js


【解决方案1】:

你可以使用Vue事件系统

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

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

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

【讨论】:

  • @GusDeCooL 该示例已被编辑。并不是说在 Vuejs 2.0 之后使用的某些方法已被弃用
  • 如果只有 1 个组件实例,效果很好,但如果有很多实例,使用 $refs.component.method() 效果更好
【解决方案2】:

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

例如

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

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

使用引用在模板/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/

【讨论】:

  • 那是因为你可能还没有定义它。看看链接的小提琴。
  • 如果您使用的是 webpack,那么您将无法访问 vm,因为它对模块进行了范围划分。您可以在 main.js 中执行类似 window.app = vm 的操作。来源:forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606
  • 对于什么是 hack 与什么是“正常”编码有如此官方的定义,但与其将这种方法称为 hack(或寻找一种“不那么 hacky”的方式来实现同样的事情),它可能是更好地质疑为什么你需要这样做。在许多情况下,使用 Vue 的事件系统来触发外部组件行为可能会更优雅,甚至可以询问为什么要从外部触发组件。
  • 如果您尝试将视图组件集成到现有页面中,可能会出现这种情况。与其完全重新设计页面,不如逐步添加额外的功能。
  • 我不得不使用这个。 : this.$refs.foo.doSomething();
【解决方案3】:

这适用于 Vue2:

var bus = new Vue()

//在组件A的方法中

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

//在组件B的created hook中

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

  // ...
})

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

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

请参阅下面 Thomas 关于 Vue 3 的评论。

【讨论】:

  • 又短又甜!如果你不喜欢全局变量bus,你可以更进一步,使用props 将总线注入到你的组件中。我对 vue 比较陌生,所以我不能向你保证这是惯用的。
  • new Vue() is deprecated in vue 3 for alternative follow this question
  • 不推荐事件总线模式(至少在 vue 2/3 中),这就是它已从文档中删除的原因。有关更多信息,您可以read this 或来自图像here 的相同信息 - 答案由skitlele(主持人,Vue 的不和谐频道的MVP)提供。 “很久以前,对事件总线的引用已从 Vue 2 文档中删除,我们最近在 Vue 3 文档中添加了一些内容以积极discourage it
【解决方案4】:

这是一个简单的

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

【讨论】:

    【解决方案5】:

    假设你在子组件中有一个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


    【讨论】:

    • 是的,你可以,但不被认为是“最佳实践”:向下到子使用属性,向上到父使用事件。要涵盖“侧向”,请使用自定义事件,或者例如Vuex。请参阅此nice article 了解更多信息。
    • 是的,不建议这样做。
    【解决方案6】:

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

    // 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');
       }
    }
    

    【讨论】:

      【解决方案7】:

      我使用了一个非常简单的解决方案。我使用 Vanilla JS 在我选择的 Vue 组件中包含了一个调用该方法的 HTML 元素,然后触发点击!

      在 Vue 组件中,我添加了如下内容:

      <span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
      

      我使用 Vanilla JS:

      const btnReload = document.querySelector('[data-id="btnReload"]');
      btnReload.click();                
      

      【讨论】:

      • 这在 vue 中根本不被认为是好的做法,尤其是在 OP 的问题中。
      【解决方案8】:

      您可以为子组件设置 ref,然后在父组件中可以通过 $refs 调用:

      给子组件添加 ref:

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

      向父级添加点击事件:

      <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
      

      var vm = new Vue({
        el: '#app',
        components: {
          'my-component': { 
            template: '#my-template',
            data: function() {
              return {
                count: 1,
              };
            },
            methods: {
              increaseCount: function() {
                this.count++;
              }
            }
          },
        }
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      <div id="app">
        
        <my-component ref="childref"></my-component>
        <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
      </div>
        
      <template id="my-template">
        <div style="border: 1px solid; padding: 2px;" ref="childref">
          <p>A counter: {{ count }}</p>
          <button @click="increaseCount">Internal Button</button>
        </div>
      </template>

      【讨论】:

      • 迄今为止最干净的解决方案。
      • 很好的答案。我只是要编辑 html 使其垂直变小一点。目前我在运行它时只能看到“内部按钮”,这可能会让人感到困惑。
      • 你可以从父组件访问一个 ref 使用这个:this.$refs.childref,例如用它来制作一个通用的警报组件
      【解决方案9】:

      已接受答案的稍微不同(更简单)的版本:

      在父实例上注册一个组件:

      export default {
          components: { 'my-component': myComponent }
      }
      

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

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

      访问组件方法:

      <script>
          this.$refs.foo.doSomething();
      </script>
      

      【讨论】:

        【解决方案10】:

        我不确定这是否正确,但这个方法对我有用。
        首先导入包含您要在组件中调用的方法的组件

        import myComponent from './MyComponent'
        

        然后调用 MyCompenent 的任意方法

        myComponent.methods.doSomething()
        

        【讨论】:

        • 这不会让您访问组件中的任何数据。如果您的doSomething 正在使用数据中的任何东西,则此方法无用。
        • @cyboashu 你是对的,但这对我来说是一个完美的主意,因为我想使用来自 mixin 的泛型方法。
        【解决方案11】:

        有时您希望将这些内容包含在您的组件中。根据 DOM 状态(当您的 Vue 组件被实例化时,您正在侦听的元素必须存在于 DOM 中),您可以在 Vue 组件内侦听组件外部元素上的事件。假设您的组件外部有一个元素,当用户单击它时,您希望您的组件做出响应。

        在 html 中你有:

        <a href="#" id="outsideLink">Launch the component</a>
        ...
        <my-component></my-component>
        

        在你的 Vue 组件中:

            methods() {
              doSomething() {
                // do something
              }
            },
            created() {
               document.getElementById('outsideLink').addEventListener('click', evt => 
               {
                  this.doSomething();
               });
            }
            
        

        【讨论】:

        • 这不是 VueJS 风格的解决方案。它绕过了 VueJS 组件系统。
        【解决方案12】:

        使用 Vue 3:

        const app = createApp({})
        
        // register an options object
        app.component('my-component', {
          /* ... */
        })
        
        ....
        
        // retrieve a registered component
        const MyComponent = app.component('my-component')
        
        MyComponent.methods.greet();
        
        

        https://v3.vuejs.org/api/application-api.html#component

        【讨论】:

          【解决方案13】:

          在这样的组件中声明你的函数:

          export default {
            mounted () {
              this.$root.$on('component1', () => {
                // do your logic here :D
              });
            }
          };
          

          并从这样的任何页面调用它:

          this.$root.$emit("component1");
          

          【讨论】:

            猜你喜欢
            • 2021-01-24
            • 1970-01-01
            • 2020-04-05
            • 2020-09-11
            • 2022-09-18
            • 1970-01-01
            • 2016-05-22
            相关资源
            最近更新 更多