Yusinto Ngadiman
September 25, 2018·1 min read

Vue Mixins With Arguments

hero

I was writing ld-vue when I needed a way to pass arguments to my Vue mixin. In my case, I needed to pass a client id to an external library so it can be initialised. This is the technique I ended up using to pass params to my mixin:

exampleMixin.js

import someLibrary from 'some-library';

const exampleMixin = clientId => ({
  methods: {
    init: function() {
      someLibrary.initialize(clientId);
    },
  },
})

export default exampleMixin

Instead of defining an object, define a function which returns the mixin object. Pass any arguments or parameters you want to this function. Then using closure, you can access these in your mixin. To use this mixin:

App.vue

<script>
import exampleMixin from './exampleMixin'

export default {
  mixins: [exampleMixin('some-client-id')],
}
</script>

Call the function with an argument which will generate the real mixin object.