从组件

时间:2015-11-12 22:29:02

标签: javascript vue.js

假设我有一个包含子组件的主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

修改

这似乎有效:

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

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

12 个答案:

答案 0 :(得分:193)

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

E.g。

在我的父实例上注册一个竞争对手:

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/

答案 1 :(得分:26)

您可以使用Vue事件系统

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

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

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

答案 2 :(得分:19)

由于Vue2适用:

var bus = new Vue()

//在组件A的方法

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

//在组件B创建的钩子

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

  // ...
})

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

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

答案 3 :(得分:6)

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

将引用添加到子组件:

<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>
  <br>
  <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
</div>
  
<template id="my-template">
  <div style="border: 1px solid; padding: 5px;" ref="childref">
    <p>A counter: {{ count }}</p>
    <button @click="increaseCount">Internal Button</button>
  </div>
</template>

答案 4 :(得分:3)

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

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

作为最佳实践,使用“道具和事件”进行亲子沟通。

如果要在组件之间进行通信,请务必使用vuexevent bus

请阅读这篇很有帮助的article


答案 5 :(得分:2)

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

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return num;
}

答案 6 :(得分:1)

接受的答案的版本稍有不同(简单):

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

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

使用参考将其呈现在template / html中:

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

访问组件方法:

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

答案 7 :(得分:0)

这是一个简单的

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

答案 8 :(得分:0)

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

import myComponent from './MyComponent'

,然后调用MyCompenent的任何方法

myComponent.methods.doSomething()

答案 9 :(得分:0)

有时您想将这些内容保留在组件中。根据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();
       });
    }
    

答案 10 :(得分:0)

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

答案 11 :(得分:-4)

我使用了一个非常简单的解决方案。我在我选择的Vue组件中使用Vanilla JS包含了一个调用该方法的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();