Подтвердить что ты не робот

Вызовите метод компонента 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>
4b9b3361

Ответ 1

В конце я решил использовать Vue ref. Это позволяет ссылаться на компонент для родителя для прямого доступа.

например.

Укомплектуйте зарегистрированный родительский экземпляр:

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

Ответ 2

Вы можете использовать систему событий Vue

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

и

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

Вот скрипка: http://jsfiddle.net/hfalucas/wc1gg5v4/59/

Ответ 3

С Vue2 это относится:

var bus = new Vue()

//в компоненте A метод

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

//в компоненте B создан хук

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

  // ...
})

Смотрите здесь для Vue документы. А вот более подробно о том, как точно настроить эту шину событий.

Если вы хотите больше информации о том, когда использовать свойства, события и/или централизованное управление состоянием, см. Эту статью.

Ответ 4

Вы можете установить ref для дочерних компонентов, тогда в parent можно вызывать через $ 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>

Ответ 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 для общения между родителями и детьми.

Если вам нужна связь между компонентами, обязательно используйте vuex или шину событий

Пожалуйста, прочитайте эту очень полезную статью


Ответ 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 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

Немного другая (более простая) версия принятого ответа:

Зарегистрируйте компонент на родительском экземпляре:

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

Визуализируйте компонент в template/html со ссылкой:

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

Получите доступ к методу компонента:

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

Ответ 8

Вот простой

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

Ответ 9

Я использовал очень простое решение. Я включил элемент HTML, который вызывает метод, в мой компонент Vue, который я выбираю, используя Vanilla JS, и я запускаю щелчок!

В компонент 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();