当前位置:首页 > VUE

vue实现新旧页面切换

2026-02-21 15:55:06VUE

路由切换动画

在Vue中可以通过<transition>组件结合Vue Router实现页面切换动画。在App.vue或布局组件中包裹<router-view>,并设置过渡样式:

<template>
  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

状态管理保存旧数据

使用Vuex或Pinia存储上一个页面的数据,在组件卸载前保存状态:

// Pinia示例
import { defineStore } from 'pinia'
export const usePageStore = defineStore('page', {
  state: () => ({
    previousPageData: null
  })
})

动态过渡效果

根据路由元信息动态切换过渡效果:

// router.js
routes: [
  {
    path: '/detail',
    component: Detail,
    meta: { transition: 'slide' }
  }
]
<template>
  <router-view v-slot="{ Component, route }">
    <transition :name="route.meta.transition || 'fade'">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

页面加载状态处理

使用路由守卫处理数据加载状态:

router.beforeEach((to, from, next) => {
  store.commit('SET_LOADING', true)
  next()
})

router.afterEach(() => {
  setTimeout(() => {
    store.commit('SET_LOADING', false)
  }, 300)
})

组件间通信

通过事件总线或provide/inject在切换时传递数据:

// 事件总线
const emitter = mitt()
emitter.emit('page-change', { from: 'oldPage', data: {...} })

// provide/inject
provide('pageContext', { prevData: {...} })

生命周期控制

利用组件的activateddeactivated钩子:

<script>
export default {
  activated() {
    // 恢复页面状态
  },
  deactivated() {
    // 保存页面状态
  }
}
</script>

滚动行为控制

在路由配置中自定义滚动行为:

vue实现新旧页面切换

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

标签: 新旧页面
分享给朋友:

相关文章

vue实现页面跳转

vue实现页面跳转

vue实现页面跳转的方法 在Vue中实现页面跳转主要有以下几种方式: 使用router-link组件 router-link是Vue Router提供的组件,用于声明式导航: <router…

vue文件实现页面跳转

vue文件实现页面跳转

使用 router-link 实现跳转 在 Vue 模板中直接使用 <router-link> 组件,通过 to 属性指定目标路径: <router-link to="/tar…

vue实现页面分页

vue实现页面分页

Vue实现页面分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,适合快速集成。以下是一个示例代码: <template>…

vue实现引导页面

vue实现引导页面

实现引导页面的方法 在Vue中实现引导页面通常需要结合用户交互和页面跳转逻辑,以下是几种常见的实现方式: 使用路由守卫控制访问权限 在router.js中配置全局前置守卫,检查用户是否首次访问:…

实现js页面跳转页面

实现js页面跳转页面

使用 window.location.href 通过修改 window.location.href 实现跳转,浏览器会加载新页面并记录到历史记录中: window.location.href = "…

jquery加载页面

jquery加载页面

jQuery 加载页面内容的方法 使用 .load() 方法 通过 AJAX 请求加载远程数据并插入到指定元素中。适用于加载部分页面片段。 $("#targetElement").load(…