Reputation: 23
I would like to call a method once, as soon as possible after its component loads, but it needs to be after a computed property that gets data from Vuex is defined.
For example:
computed: {
my_data: function() {
return this.$store.state.my_data;
}
},
methods: {
useData: function(){
axios.post('api/fetch', {'data': this.my_data});
}
},
mounted() {
this.useData(); //error: this.my_data is undefined;
},
watch: {
my_data: function(){
this.useData(); //never triggers
}
}
If I call this.useData() from mounted, my_data is still undefined. I tried setting a watcher on my_data, but it never triggers. I feel like I'm missing something obvious here.
Upvotes: 0
Views: 1331
Reputation: 23
It turns out the "undefined" error was caused by another object that shared a key name with my stored object. Unfortunately, the nebulous error message sent me on a wild goose chase after I assumed the stored object was the issue based on my inexperience with Vuex.
Upvotes: 0
Reputation: 1544
Make sure the data in my_data
is updating correctly in store. If still have issue, then use deep
to watch my_data
watch:{
my_data:{
handler:function(){
this.userData();
},
deep:true
}
}
If you're using watch to trigger method, don't need to use to call it from the mounted
.
Upvotes: 1