How to access function inside methods of mixin from component lifecycle method in Vue.js

Viewed 4905

Here is an example :

mixin.js

export default {
    methods : {
        aFunction() { // Some functionality here }
    }
}

component.vue

import mixin from './mixin'
export default {
    mixins : [ mixin ]
    created() {
        // Call aFunction defined in the mixin here
    }
}

I want to access the aFunction defined inside methods of mixin from the created() lifecycle method inside the component.

1 Answers

The mixin methods are merged with the current instance of the component, so it would just be:

created(){
  this.aFunction()
}

Here is an example.

console.clear()

const mixin = {
  methods:{
    aFunction(){
      console.log("called aFunction")
    }
  }
}

new Vue({
  mixins:[mixin],
  created(){
    this.aFunction()
  }
})
<script src="https://unpkg.com/vue@2.4.2"></script>

Related