javascriptvue.jsvuejs2namespacesmixins

Vue2 - What does a public/private method implementation look like in mixins?


I see that the following are documented, but I have trouble visualizing how this can be implemented.

// Even better!
var myGreatMixin = {
  // ...
  methods: {
    publicMethod() {
      // ...
      myPrivateFunction()
    }
  }
}

function myPrivateFunction() {
  // ...
}

export default myGreatMixin

The issue I am having is that in a component that contains multiple mixins, how do we manage them, what is the best practice/conventions here?

I understand how this would fix the issue I've mentioned.

var myGreatMixin = {
  // ...
  methods: {
    $_myGreatMixin_update: function () {
      // ...
    }
  }
}

However, as the question states, I am trying to understand how the even better approach can be implemented in a component.

My wild idea, not sure if this would even work/make sense?


// myMixin
const method1 = () => console.log('method1 firing')

export default {
  methods: {
    $_myMixin() {
      return {
        method1 
      }
    }
  }
}


// component
mixins: [myMixin],

data: () => ({
  myMixinMethods: {}
}),
created() {
  this.myMixinMethods = this.$_myMixin()
},
mounted() {
  this.myMixinMethods.method1()
}

It feels convoluted, so I went out searching for more answers and saw that there was an even better approach, perhaps with the pubic/private methods, but unfortunately, I don't quite understand how that is implemented, and if it would solve my namespace issue with multiple mixins in a vue component.


Solution

  • In Vue 2, there is no built-in concept of "private" methods, but you can mimic this behavior by defining functions outside the component or mixin object, just like in the example you've provided. These functions will not be accessible from other components or mixins, effectively making them "private".

    The "even better" approach you've mentioned involves defining a private function outside the mixin object. This function is only accessible within the same file/module and is not exposed when the mixin is imported into a component. Here's an example of how you might use this approach:

    So, define mixin like this:

    function privateMethod() {
      console.log('Private method firing');
    }
    
    export default {
      methods: {
        publicMethod() {
          console.log('Public method firing');
          privateMethod();
        }
      }
    }
    

    and on the component:

    import myMixin from './myMixin';
    
    export default {
      mixins: [myMixin],
      mounted() {
        this.publicMethod(); // This will call both the public and private methods
      }
    }
    

    So, you can some how mimic the behavior like that.