Answer the question
In order to leave comments, you need to log in
How to run a method on page load?
When the project is initialized, information about the authorized user is requested.
At this time, in the component, you need to download the news for the user, but for this you first need to get his id.
Theoretically, the request for user information may hang and at the time the component is loaded, the user id information may still be missing.
So this approach won't work:
//component
...
created() {
this.$axios.post('/news', {user_id: this.$store.state.user.id})
}
//component
...
watch: {
'$store.state.user': function() {
this.$axios.post('/news', {user_id: this.$store.state.user.id})
}
}
//component
...
watch: {
'$store.state.user': function() {
this.loadNews();
}
},
created() {
this.loadNews();
},
methods: {
loadNews() {
this.$axios.post('/news', {user_id: this.$store.state.user.id});
}
}
Answer the question
In order to leave comments, you need to log in
//component
...
watch: {
'$store.state.user': {
handler() {
this.loadNews();
},
immediate: true
}
},
methods: {
loadNews() {
this.$axios.post('/news', {user_id: this.$store.state.user.id});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question