vue3 vue-router过渡动效  滚动行为 (四)

文章目录

  • 一、过渡动效
    • 1.1安装animate.css
    • 1.2 利用元信息存储过渡名称
    • 1.3 在组件中使用
  • 二、滚动行为
    • 2.1 始终滚动到顶部
    • 2.2 相对于某个元素的偏移量
    • 2.3 保持之前的滚动位置

一、过渡动效

1.1安装animate.css

npm install animate.css --save

1.2 利用元信息存储过渡名称

{path: "/home",name: "home",alias: "/index",component: () => import("@/views/home/index.vue"),meta: { transition: "animate__tada" },},{path: "/about/:id",name: "about",meta: { transition: "animate__backInDown" },component: () => import("@/views/about/index.vue"),},

1.3 在组件中使用

注意:不能直接transition包裹router-view,会发生以下的报错

以下式错误写法!!!

<transition:duration="500"leave-active-class="animate__animated animate__fadeOutUp"enter-active-class="animate__animated animate__fadeInLeft"><router-view></router-view></transition>

在这里插入图片描述
<router-view>不能再直接在内部使用<transition><keep-alive>


正确写法!!!

<router-view v-slot="{ Component, route }"><transition:duration="500"leave-active-class="animate__animated animate__fadeOutUp"enter-active-class="animate__animated animate__fadeInLeft"><component :is="Component" :key="route.path" /></transition></router-view>

二、滚动行为

使用 Vue Router 中的滚动行为(Scroll Behavior)来控制页面切换时的滚动位置。当用户在页面之间导航时,页面可以自动滚动到指定的位置,从而提供更好的用户体验

  • to:表示即将进入的目标路由对象。
  • from:表示当前导航正要离开的路由对象。
  • savedPosition:只有在使用浏览器前进/后退按钮时才可用,用于记录滚动位置
const router = createRouter({history: createWebHashHistory(),routes: [...],scrollBehavior (to, from, savedPosition) {// return 期望滚动到哪个的位置}
})

2.1 始终滚动到顶部

const router = createRouter({scrollBehavior(to, from, savedPosition) {// 始终滚动到顶部return { top: 0 }},
})

2.2 相对于某个元素的偏移量

const router = createRouter({scrollBehavior(to, from, savedPosition) {return {// 也可以这么写// el: document.getElementById('main'),el: '#main',top: -10,}},
})

2.3 保持之前的滚动位置

const router = createRouter({scrollBehavior(to, from, savedPosition) {if (savedPosition) {return savedPosition} else {return { left: 0, top: 0 }}},
})