Vue应用借助vuex-persistentstate实现来源页返回功能求助
实现Vue页面跳转后返回来源页(基于vuex-persistedstate)
以下是结合你现有配置的完整实现步骤:
1. 在路由守卫中记录来源页
在路由配置文件(src/router/index.js)中添加全局前置守卫,当从页面A/B/C跳转到页面D时,将来源页路径存入Vuex:
import router from './router' import store from '@/store' router.beforeEach((to, from, next) => { // 替换成你页面D实际的路由name或path if (to.name === 'PageD') { // 排除直接访问D页的情况,仅记录从A/B/C过来的路径 if (from.path !== '/' && !from.path.includes('pageD')) { store.dispatch('global/setPageAfterFinishClick', from.path) } } next() })
2. D页面按钮点击时返回来源页
修改页面D中“取消/完成”按钮的点击逻辑,从Vuex取出记录的来源页并跳转:
选项式API写法
<template> <button @click="handleCancel">取消</button> <button @click="handleFinish">完成</button> </template> <script> export default { methods: { handleCancel() { this.navigateBack() }, handleFinish() { // 先执行完成业务逻辑 // ...你的业务代码 this.navigateBack() }, navigateBack() { const sourcePath = this.$store.state.global.pageAfterFinishClick this.$router.push(sourcePath) } } } </script>
组合式API写法
<template> <button @click="handleCancel">取消</button> <button @click="handleFinish">完成</button> </template> <script setup> import { useRouter, useStore } from 'vuex' const router = useRouter() const store = useStore() const navigateBack = () => { const sourcePath = store.state.global.pageAfterFinishClick router.push(sourcePath) } const handleCancel = () => navigateBack() const handleFinish = () => { // ...你的业务代码 navigateBack() } </script>
3. 边界情况兜底
如果用户直接访问页面D(无来源页记录),确保仍能跳转至首页:
// 在跳转逻辑中添加兜底 const navigateBack = () => { const sourcePath = store.state.global.pageAfterFinishClick router.push(sourcePath || '/') }
现有代码补充说明
确保你的src/store/global/index.js中已定义mutation常量:
export const SET_PAGE_AFTER_FINISH_CLICK = 'SET_PAGE_AFTER_FINISH_CLICK'
内容的提问来源于stack exchange,提问作者Haidepzai
相关产品推荐
相关产品推荐

