Passing a prop to a vuejs mixin but property is undefined

nunos picture nunos · Nov 22, 2019 · Viewed 8.7k times · Source

When I try to pass a prop to a mixin I get a Cannot read property of undefined error.

Am I doing something wrong or how else can I overcome this?

mixins/BarMixin.js:

export default baz => {
  return {
    // my mixin code...
  }
}

components/FooComponent.vue:

<script>
import BarMixin from '@/mixins/BarMixin.js'

export default {
  mixins: [BarMixin(this.baz)],
  props: {
    bar: {
      type: Boolean,
      required: true,
    },
  },
}
</script>

and then I try to use it, in something like this:

pages/foo.vue

<template>
  <FooComponent :baz="true" />
</template>

<script>
import FooComponent from '@/components/FooComponent.vue'
export default {
  components: {
    FooComponent,
  },
}
</script>

Answer

Vagner Gon picture Vagner Gon · Jun 26, 2020

You can workaround by accessing these properties from the component as if the mixing is the component. To make the property 'dynamic', you can pass the name of the field you need to access inside the mixin. Like this:

function myMixin(propName) {
  return {
    computed: {
      mixinComputed () {
        return this[propName] + 'somethingElse';
      }
    }
  };
}

If you want to pass an inner property of an object, like 'user.name' to the mixin, you can create a computed on the outer component or, make it inside the mixin itself:

function myMixin(propName1, propName2) {
  return {
    computed: {
      mixinComputed () {
        return this.parsedPropValue1 + this.parsedPropValue2;
      },
      parsedPropValue1 () {
        return this.parsePath(propName1);
      },
      parsedPropValue2 () {
        return this.parsePath(propName2);
      }
    },
    methods: {
      parsePath(path) {
        if (!path)
         return;
        const split = path.split('.');
        return split.reduce((acc, curr) => acc && acc[curr], this);
      }
    }
  };
}

Usage:

mixins: [myMixin('user.address.street', 'obj')]