3

I can't call mixin method from the component, I get this error this.hello is not a function.

I can call hello() from Vue instance but I can't call it within the component.

What's a matter?!

<div id='vue-app'>
  <cmp></cmp>
</div>
const mixin = {
  methods: {
    hello() {
      return 'Hello World!';
    }
  },
  created() {
    console.log('Mixin Created!');
  },
};

const cmp = {
  created() {
    console.log('From Cmp:', this.hello());
  },
};

new Vue({
  components: {
    cmp
  },
  el: '#vue-app',
  mixins: [mixin],
  created() {
    console.log('From VM:', this.hello());
  },
});

https://jsfiddle.net/ar464soq/

Yaser Khahani
  • 685
  • 7
  • 15

3 Answers3

5

Correct, mixin methods/data are only available with in the instance its added to. However if you really want the mixin in your root intstance you can call this.$root.hello() from any child component of the root instance

daxigu
  • 59
  • 2
2

Well, it seems I have to load the Mixin throughout of the Component instance, not from Vue parent instance :)

Yaser Khahani
  • 685
  • 7
  • 15
  • is there a way we just need to declare on vue parent, so we do need to redeclare it again in child component? – hendra1 Feb 22 '18 at 10:28
0

If you use nuxt with vue @daxigu won't work because the $root is nuxt it self. What can I do? This:

this.$root.$children[1].myRootMethod()
  • $root: As I said before, this is nuxt.

  • $children[0]: is nuxtloading.

  • $children[1]: is your main component, in my case, it was a base layout with a few global components and a global mixin.

Hope it helps.

mrroot5
  • 1,811
  • 3
  • 28
  • 33