Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 627
Gaurav Sarma Avatar asked Sep 25 '17 20:09

Gaurav Sarma


People also ask

How do you use mixin in composition API?

To use the Mixin in any component, you simply have to import the Mixin module and assign it to the mixins configuration property in the component. At runtime, the options specified in the Mixin will be available as options and will be “mixed” into the consuming component's options.

What is the priority of hooks defined in mixins?

// => "mixin hook called" // => "component hook called" Options that expect object values, for example methods , components and directives , will be merged into the same object. The component's options will take priority when there are conflicting keys in these objects: var mixin = {

Which of the following is a core feature of mixins in VUE JS?

15) Which of the following is a core feature of Mixins in Vue. js? Mixins provide great flexibility. Mixin contains options for Vue.


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/[email protected]"></script>
like image 127
Bert Avatar answered Nov 14 '22 23:11

Bert