How to reuse a method: define in main object and call from all component in VueJS

448 views Asked by At

I use parent child components with vueJs. I currently have to define a method individually for more than one component.

But, I just want to define it at a single place and use on multiple locations.

My Parent Template is,

<campaign_segment :a=add(1,2)> </campaign_segment>

Parent Template's Source,

<template v-if="showTemplate" id="segment_body"> </template>

In VueJS,

   Vue.component(
   'campaign_segment', {
     template: '#segment_body',
     props: ['a'],
     methods:{
       add: function(a,b){
          return parseInt(a) + parseInt(b);
       }
     }
  });

Here, I should define the method "add()" to my main vuejs object.

Otherwise i get error message as "add method is not defined".

Is there any solution for single declaration, and trigger from components ?

How is it possible or any other solution for this ?

1

There are 1 answers

0
Saurabh On

The feature you are looking for is called mixins in vue JS.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

So you can add a method in mixin and it will be available in all the components, where mixin will be mixed. See following example:

// define a mixin object
var myMixin = {
  methods: {
       add: function(a,b){
          return parseInt(a) + parseInt(b);
       }
  }
}

// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})

// alternate way to have a mixin while initialising
new Vue({
  mixins: [myMixin],
  created: function () {
    console.log('other code')
  }
})