PuffedRiceCrackers
PuffedRiceCrackers

Reputation: 785

How do I call a mixin function from another component?

MyMixin.vue has the method beginEdit.

What I'm trying to do is to make onFirstLineClick to call myMixin's beginEdit depending on the value of this.folded.

When I console logged myMixin.beginEdit, it is undefined and not surprisingly myMixin.beginEdit() doesn't work.

Am I missing something needed to use the function? If so, why does beginEdit work perfectly on <span>?

<template>
  <div>
    <div>
      <div
        @click="onFirstLineClick"
      />
      <span
        @click="beginEdit"
      />
  </div>
</template>

<script>
import myMixin from './MyMixin';

export default {
  name: 'currComponent',
  mixins: [myMixin],
  data() {
    return {
      folded: false,
    };
  },
  methods: {
    onFirstLineClick(e) {
      // myMixin.beginEdit() doesn't work
    }
  },
};
</script>

Upvotes: 1

Views: 1551

Answers (1)

palaѕн
palaѕн

Reputation: 73896

The great thing about mixin is that when a component uses a mixin, all options in the mixin will be "mixed" into the component's own options. Which means that inside your component you can call mixin method directly like:

methods: {
  onFirstLineClick(e) {
    this.beginEdit()
  }
},

That is also the reason why you can use beginEdit() method on <span> directly like:

<span @click="beginEdit" />

Please also know that in future if you declare a method in this component with same name as mixin method name beginEdit, then the component's method will take priority and you might see different behaviour. So, make sure to give unique names to mixin methods.

Upvotes: 2

Related Questions