Use <transition> on <router-view>

vue
transition
router-view

新版vue router在<transition>與<router-view>的搭配使用上,規定<transition>不可以再包在<router-view>外面


警告訊息如下:

[Vue Router warn]: <router-view> can no longer be used directly inside <transition> or <keep-alive>.
Use slot props instead:

<router-view v-slot="{ Component }">
  <transition>
    <component :is="Component" />
  </transition>
</router-view>


在實作時,各頁切換嘗試加入<transition>過場動畫

HTML

<router-view v-slot="{ Component }" :key="$route.fullPath">
      <transition name="route" mode="out-in">
        <component :is="Component" />
      </transition>
</router-view>

CSS

.route-enter-from {
  opacity: 0;
  transform: translateY(-30px);
}
.route-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
.route-enter-active {
  transition: all 0.3s ease-out;
}
.route-leave-active {
  transition: all 0.3s ease-in;
}
.route-enter-to,
.route-leave-from {
  opacity: 1;
  transform: translateY(0);
}


設定mode = " out-in "可讓component等待完全消失後再進入,避免同時執行動畫動作


原先沒有加上key attribute


遭遇主頁有畫面,但點擊至其他routes後,path有改變,但內容卻一片空白


一開始以為是不是專案內的Bootstrap的Carousel造成BUG,但發現不是...


嘗試移除了<transition>,便能正常依route path切換顯示的components


查了許多文章沒有找到完全符合我的這樣情況的解法


後來嘗試這篇內所描述關於<router-view>渲染的觀念


加上:key = " $route.fullPath " 後,便能正常切換路徑、顯示頁面內容了




至於為何明明我的例子並非children component導致無法渲染,但在加入<transition>後才出現BUG


我還是沒搞懂..O_oa

© 2021 Hamsterism. All rights reserved github