Vue 转换不适用于 router-link 和 $router.push

Nrg*_*zer 0 javascript vue.js vue-transitions

我有以下 App.vue 文件:

<script setup>
import { RouterView } from "vue-router";
</script>

<template>
  <RouterView v-slot="{ Component }">
    <transition :name="fade" mode="out-in">
      <component :is="Component" />
    </transition>
  </RouterView>
</template>
Run Code Online (Sandbox Code Playgroud)

以及以下路由器文件:

import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "signin",
      component: () => import("../views/signin.vue"),
    },
    {
      path: "/dashboard",
      name: "dashboard",
      component: () => import("../views/dashboard.vue"),
    },
  ],
});

export default router;
Run Code Online (Sandbox Code Playgroud)

当我运行我的应用程序并单击任何链接时,无论它是否使用$router.push("/dashboard");或,都不会发生任何转换router-link(to="/dashboard" active-class="active")。我已经检查了许多其他问题和教程,但不幸的是它仍然不起作用。知道为什么没有发生转换吗?

Chr*_*ula 7

您可以在代码中更改一些内容。

首先,您不需要声明导入,因为RouterView它是全局注册的。只要vue-router安装在您的项目中,您就可以安全地使用RouterViewrouter-view直接在您的模板上使用。

其次,您需要将nameprop 更改为静态 prop。写入:name="fade"意味着您将变量的值传递fadename. 根据您的代码,我假设fade不是变量而是字符串,这意味着您需要将 prop 更改为name="fade". 阅读有关静态和动态道具的更多信息。

最后,过渡需要使用 CSS。由于您要声明一个命名的过渡,因此需要添加以下CSS:

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)

fade注意CSS 中的使用。这是 prop 中提供的值,name这意味着如果您有例如:

<transition name="slide-in" mode="out-in">
Run Code Online (Sandbox Code Playgroud)

那么你的 CSS 应该有.slide-in-enter-active, .slide-in-enter-leave, 等等。


JCo*_*ode 5

改变:

<component :is="Component" />
Run Code Online (Sandbox Code Playgroud)

<component :key="$route.path" :is="Component"/>
Run Code Online (Sandbox Code Playgroud)

转换没有检测到视图的变化,因此您需要提供一些可以改变的内容。另外,请记住,它fade必须是 CSS 中的实际动画,例如:

    .fade-enter-active
    {
        animation: fade 0.25s;
    }

    .fade-leave-active
    {
        animation: fade 0.25s reverse;
    }

    @keyframes fade 
    {
        from
        {
            opacity: 0%;
        }

        to
        {
            opacity: 100%;
        }
    }
Run Code Online (Sandbox Code Playgroud)