0
votes

I am using Vue, Vuex, and Vue-router. There is a list of router-link elements. When clicked, the component in the router-view area should switch with animation and the route url should change. In other words, the old component should disappear completely, then there is a request to the server for data for the new component, and then the new component appears smoothly. But this does not happen. After clicking on the router-link, the data for the new route is loaded quickly and the NEW component disappears smoothly, then it appears smoothly.

What am I doing wrong that a new component disappears? I make a request for data in the beforeRouteEnter and beforeRouteUpdate hooks.

LessonsList.vue

<template>
  <section>
    <ul>
      <router-link 
          v-for="(lesson,index) in lessons"
          v-bind:key="index"
          :to="{
             name: 'lesson',
             params: {
               id: index+1
             }
           }"
           tag="li"
      >
        <h2>№{{index+1}}</h2>
      </router-link>
    </ul>
    <transition name="slide" mode="out-in" appear>
            <router-view :key="$route.path"></router-view>
    </transition>
  </section>

Lesson.vue

import {store} from '../../vuex/store'
    
beforeRouteEnter(to, from, next) {
  let sendData = {};
  sendData.lessonNumber = Number(to.params.id);
  sendData.userId = store.getters['login/userId'];
  store.dispatch('lesson/changeCurrentLesson', sendData).then(()=> next());
  //dispatch action to vuex for data fetching
},
beforeRouteUpdate(to, from, next){
  let sendData = {};
  sendData.lessonNumber = Number(to.params.id);
  sendData.userId = store.getters['login/userId'];
  store.dispatch('lesson/changeCurrentLesson', sendData).then(()=> next());
}
1
This is the exact problem I am having. It appears that that "slide" type transitions do not do well with data-fetching routes. I want to slide out the old component/data, start data fetch (showing nothing) and slide in new component/data. But there's no way to sync that sequence with the transition. - tarponjargon

1 Answers

0
votes

After clicking on the router-link, the data for the new route is loaded quickly and the NEW component disappears smoothly, then it appears smoothly.

I guess this happens because you are using a single state let's call currentLesson when you navigate to the new route (same route different params) then beforeRouteUpdate will trigger on old component then update currentLesson so you will see it looks like the new component disappears. Then the real new component appears with the same currentLesson.

Example

So you can solve this problem by use the lesson object with its own key or number. Or instead of using beforeRouteEnter and beforeRouteUpdate hooks, you can use created or mounted hooks which I think it's better if you need to show some contents before the API loaded.

Example