IT story

컴포넌트 외부에서 Vue.js 컴포넌트 메소드 호출

hot-time 2020. 5. 24. 11:01
반응형

컴포넌트 외부에서 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()메서드가 클릭 이벤트에 바인딩되어 호출됩니다. jQuery로 수신 대기중인 클릭 이벤트를 외부 버튼에 바인딩 할 수있는 방법이 없으므로을 호출하는 다른 방법이 필요합니다 increaseCount.

편집하다

이것이 작동하는 것 같습니다 :

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

그러나 자식 배열의 색인으로 구성 요소를 참조하고 있기 때문에 이것은 좋은 해결책이 아니며 많은 구성 요소를 사용하면 일정하게 유지되지 않고 코드를 쉽게 읽을 수 없습니다.


결국 나는 Vue의 ref지시문 을 사용하기로 결정했습니다 . 이를 통해 구성 요소를 상위에서 참조하여 직접 액세스 할 수 있습니다.

예 :

부모 인스턴스에 compenent를 등록하십시오.

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/ 사용하는 예 )


Vue 이벤트 시스템을 사용할 수 있습니다

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

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

여기 바이올린이 있습니다 : http://jsfiddle.net/hfalucas/wc1gg5v4/59/


Vue2부터 적용됩니다 :

var bus = new Vue()

// 컴포넌트 A의 메소드에서

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

// 컴포넌트 B의 후크 생성

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

  // ...
})

Vue 문서는 여기참조 하십시오 . 그리고 여기에 바로이 이벤트 버스를 설정하는 방법에 대한 자세한 내용입니다.

If you'd like more info on when to use properties, events and/ or centralized state management see this article.


A slightly different (simpler) version of the accepted answer:

Have a component registered on the parent instance:

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

Render the component in template/html with a reference:

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

Access the component method:

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

You can set ref for child components then in parent can call via $refs:

Add ref to child component:

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

Add click event to parent:

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


Say you have a child_method() in the child component:

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

Now you want to execute the child_method from parent component:

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

If you want to execute a parent component method from child component:

this.$parent.name_of_method()

NOTE: It is not recommended to access the child and parent component like this.

Instead as best practice use Props & Events for parent-child communication.

If you want communication between components surely use vuex or event bus

Please read this very helpful article



This is a simple way to access a component's methods from other component

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

Here is a simple one

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

I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!

In the Vue Component, I have included something like the following:

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

That I use using Vanilla JS:

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

참고URL : https://stackoverflow.com/questions/33682651/call-a-vue-js-component-method-from-outside-the-component

반응형