Can you access component data from within a mixin?

I made this fiddle to demonstrate my problem

https://jsfiddle.net/duq7txhf/

thanks a lot!

I’ve resorted to using this.$options because custom options are available in the mixin but apparently not data properties?

bumpidy bump bump

Well… I don’t understand why you have to do this.
Obviously, this.test1 and this.test2 are undefined.
You can’t access the vue instance in the mixin.

Actually

var mixin={
    	data(){
      	return {
        	debug: this.test1,
        	test2: this.test1 + 1
        }
      }	
    }
new Vue({
  el: '#app',
  mixins: [mixin],
  data(){
  	return {
    	test1: 1,
    }
  }
})

But you can access props which I find odd

What do you mean?

https://jsfiddle.net/4zdok6qh/2/

You can observe from this life cycle.

The props is already.

 beforeCreate(){
  console.log(this.$options);
 }

Yeah but what about data!!!

I thought the data would be accessible, I’ll just have to use the $options method

Did you mean use this.$options.test1?

@lopu You can’t do what you are trying to do because data() from the mixin is run before data from the component itself, so this.test1 doesn’t exists yet on the component instance, it is added after the mixin’s data has run.

in other mixin options you could access it, e.g. in a created lifecycle hook.

2 Likes

@LinusBorg feels dirty doing it in a created lifecycle hook.

I find it interesting that this.$options.X is available but not this.$options.data but I get why, it’s due to the registering of data properties upon loading but does the order really matter, I guess it does because the mixin wants to use it’s own data before merging, you could have something like this.$options.nativeData possibly.

Thanks for the reply anyway!