W
W
WebDev2018-12-19 13:33:03
Vue.js
WebDev, 2018-12-19 13:33:03

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})
}

Then you can run this method in watch:
//component
...
watch: {
    '$store.state.user': function() {
            this.$axios.post('/news', {user_id: this.$store.state.user.id})
    }
}

But this method will not work if the information has already loaded at the time the component is loaded.
Then the third option:
//component
...
watch: {
    '$store.state.user': function() {
           this.loadNews();
    }
},
created() {
    this.loadNews();
},
methods: {
    loadNews() {
        this.$axios.post('/news', {user_id: this.$store.state.user.id});
    }
}

But this code looks redundant.
How to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin Malyarov, 2018-12-19
@Konstantin18ko

beforeCreate

F
fl3nkey, 2018-12-19
@FLUNKEY

//component
...
watch: {
    '$store.state.user': {
         handler() {
             this.loadNews();
         },
         immediate: true
     }
},
methods: {
    loadNews() {
        this.$axios.post('/news', {user_id: this.$store.state.user.id});
    }
}

N
nvdfxx, 2018-12-19
@nvdfxx

So this approach won't work:
//component
...
created() {
    this.$axios.post('/news', {user_id: this.$store.state.user.id})
}

Why won't it work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question