Call a VueJS method inside a component outside 'export default'

Viewed 21659

I'm trying to call a function inside 'method' from outside. However, it isn't working.

Github issue reporting the same: https://github.com/vuejs/vue/issues/329

vm.test(); // call a function in method, not working
this.vue.test()  // not working
export default {
  methods: {
    test: function() {
      alert('test fuction called');
    }
  }
}
4 Answers

This is the way I solved that problem.

For the purpose of this demonstration, we create a new project using Vue/CLI. After installation finished, we make the vm exposed to global. Open src/main.js and edit like so:

src/main.js

import Vue from 'vue';
import App from './App.vue';

var vm = new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

// Add this line (tambahkan baris berikut):
window.vm = vm;

Leave the generated App.vue like it is. So the first child of vm (vm.$children[0]) is App.vue.

We see that App.vue have a child. That makes HelloWorld.vue component as a grand children of vm (vm.$children[0].$children[0]). Knowing this, we can call the methods from outside 'export default' like this:

src/components/HelloWorld.vue

<template>
  <div class="hello">
    <button 
      id="sebuahButton" 
      class="btn btn-outline-secondary btn-sm" 
      type="button"
    >Click Me, Jose!</button>
    <h1>{{ msg }}</h1>
    <!-- and some stuff, vue cli default generated code -->
  <div>
</template>

<script>
(function() {
    // wait for the DOM ready event in plain JavaScript
    document.addEventListener("DOMContentLoaded", event => {
        document.getElementById("sebuahButton").onclick = function() {
            vm.$children[0].$children[0].someAction();
        };
    });
})();

export default {
    name: "HelloWorld",
    props: {
        msg: String
    }
    methods: {
        someAction () {
            // do something (lakukan sesuatu masbro!)
            console.log("It's been called from outer space, Luke!");
        }
    }
}
</script>
Related