Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
    }
  }
}
like image 261
Gijo Varghese Avatar asked Jul 03 '17 13:07

Gijo Varghese


2 Answers

It is not very clear what the actual goal of the original poster is, however this is how you can call a method on a Vue instance, after creating it:

var viewModel = new Vue({
    el: "#app",
  data: {
    msg: "Hello there"
  },
  methods: {
    test: function() {
      alert('test fuction called');
    }
  }
});

viewModel.test();

Working example: https://jsfiddle.net/Daryn/Lja7pake/3/

If you are exporting a single file component then try this:

example.js

<script>
   export default {
    methods: {
      test: function() {
      alert('test fuction called');
     }
    }
   }
</script>

main.js

<script>
    import Thing from './example.js';
    Thing.test();
</script>

Reference: https://vuejs.org/v2/guide/single-file-components.html

like image 59
Daryn Avatar answered Sep 17 '22 20:09

Daryn


What you are trying to achieve is fundamentally flawed. You can't call a method of a component unless you have a reference to an instance of that particular component. In your code, which particular component is vm referring to?

All you're doing is exporting a Vue component definition from your module; there's no component being instantiated here.

We'll need to see more of your code or a complete explanation of what exactly you're trying to achieve so we can provide an alternative solution. (Why are you trying to call the component's method outside of its definition?)

like image 22
Decade Moon Avatar answered Sep 17 '22 20:09

Decade Moon