S
S
Spoon in the brain2020-02-23 13:53:28
Vue.js
Spoon in the brain, 2020-02-23 13:53:28

What is the best hook to load data with axios?

Guys, this problem has already tortured me.
In general, before / after switching to a certain router, I need to load information from the server, I used a lot of hooks from created to beforeRouteEnter , but it doesn’t work, it loads information, for example, in the mount hook after I completely reload the page. This is very disappointing, since you don’t want to use vuex for all sorts of small things. How to solve this problem? And I'm sorry for the stupid question, I climbed through the documentation, googled a lot, even printed out this image:
5e5259684be0d040821868.png
But alas, either I'm so stupid, or is there some kind of catch in it ... Help!

UPD.
I will give an example of one of the routers.

<template>
    <div class="UserProfilePostsCont">
        <div class="UserProfilePosts">
            <div class="UserProfilePost" v-for="PostData in postsData" :key="PostData.id">
                <hr>
                <p>{{PostData.Content}}</p>
                <hr>
            </div>
        </div>
    </div>
</template>

<script>
export default{
    data: function(){
        return{
            postsData: null
        }
    },
    beforeMount(){
        //подгружает только после полного обновления страницы, 
        //но никак не подгружает после перехода через <router-link/>
        const Login = this.$route.params.login
        this.$axios.post(this.$server+'getposts', {'Login': Login})
       .then(resp=>{
           this.postsData = resp.data.Posts
       })
   }
}
</script>


UPD.
By the way, I use nested routers + code.
{
      path:'/user/:login',
      name:'UserPage',
      component:UserPage,
      children:[
        {
          path:'',
          name:'UserProfilePosts',
          component:UserProfilePostsCom
        }
      ]
    }

Based on the documentation, the empty path of the subrouter will become the "main page" of the main router, but something does not happen in my case...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2020-02-23
@AndrewRusinas

The official documentation says mounted(). I also use it there all the time, no problems)
Proof
As for loading information when moving along routes, but without changing the component, use:

watch: {
   '$route' (from, to) {
      if (from.path !== to.path) { // или любое другое условие
           axios.getSomethingFromBackend()
      }
   }
}

The code may be inaccurate, but the point is to watch the route change and call the necessary actions, since transitions like from /blog/post_id to /blog/another_post_id do not fire hooks.

D
Dima Pautov, 2020-02-23
@bootd

created

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question