meteor-vue / vue-meteor-tracker

Use Meteor Tracker reactivity inside Vue components
90 stars 20 forks source link

this undefined in Reactive data #77

Open harry-73 opened 2 years ago

harry-73 commented 2 years ago

I use vue3 and vue-meteor-tracker 3.0.0beta7.

When I try to use 'this' in Reactive data, i got undefined.

In fact, it works when I use for example 'this.$store...' but not if I use 'this' with variables defined into 'data()' or 'computed()'.

harry-73 commented 2 years ago

if the variable is coming from a prop it is OK:

export default { props: { id: { type: [String], required: true }, },

data() { return { fromData: 'foo' }; },

meteor: { test() { console.log('Prop: ', this.id); // Result: OK console.log("FromData", this.fromData); // Result: undefined // code } } }

harry-73 commented 2 years ago

all reactive data, computed properties are undefined the fisrt time test() is called. The next time, it is OK.

It seems VueMeteor is added before created() of the component so all reactive data, computed properties are not yet been set up.

jamesgibson14 commented 1 year ago

That is correct, vueMeteor uses beforeCreate https://github.com/meteor-vue/vue-meteor-tracker/blob/441a6ad2b125862a804e1a7b394a521749a14990/src/index.ts#L204C24-L204C24 I just ran into this problem and in Vue3 beforeCreate is run before the data() / computed() functions which means reactive dependencies are not setup. You can bypass it by creating your reactive variable in the setup(). Or a fix might be to change vueMeteor to use the "created" hook instead of "beforeCreate".