【前端分享】vue开发项目,如何实现 从A页面跳转到B页面,并传值!
Vue 页面双向跳转传值A↔B完整实现在 Vue 中实现A → B → A 并携带参数回传核心用Vue Router配合路由传参最常用两种方案编程式导航 query/params 传参简单场景、路由守卫 状态管理复杂场景。我直接给你最实用、开箱即用的实现方法分步骤写清楚。一、准备工作路由配置先确保你的router/index.js配置好 A、B 页面路由import Vuefromvue importRouterfromvue-router importPageAfrom/views/PageA importPageBfrom/views/PageB Vue.use(Router) exportdefaultnewRouter({ routes: [ { path: /, name: PageA, component: PageA }, { path: /pageB, name: PageB, component: PageB } ] })二、核心实现A → B → A 回传参数方案1最简单 —— 路由 query 传参推荐新手适用简单字符串、数字等小数据URL 会显示参数无隐私。步骤1A 页面跳转到 B 页面PageA.vue发送方template div h2A 页面/h2 button clickgoToB跳转到 B 页面/button /div /template script export default { methods: { goToB() { // 跳转到 B 页面可携带参数给 B this.$router.push({ path: /pageB, query: { from: A页面 } // 传给 B 的参数 }) } } } /script步骤2B 页面接收参数再跳回 A 并传值PageB.vue中转回传template div h2B 页面/h2 p来自 A 的参数{{ $route.query.from }}/p button clickbackToA跳回 A 页面并传递消息/button /div /template script export default { methods: { backToA() { // 跳回 A**携带回传参数** this.$router.push({ path: /, query: { msg: 我是B页面传回的消息, status: success } }) } } } /script步骤3A 页面接收 B 传回的消息PageA.vue接收回传参数script export default { // 监听路由变化必须加否则页面不刷新拿不到参数 watch: { $route(to) { this.getMsgFromB(to.query) } }, mounted() { // 初始化也获取一次 this.getMsgFromB(this.$route.query) }, methods: { getMsgFromB(query) { if (query.msg) { console.log(B 传回的消息, query.msg) alert(query.msg) // 你可以渲染到页面、存储到变量等 } } } } /script方案2隐私数据 —— params 传参URL 不显示适用不想让参数暴露在 URL 中必须用路由 name跳转。A 跳 Bthis.$router.push({ name: PageB, // 必须用 name params: { id: 1001 } })B 跳回 A 并传参this.$router.push({ name: PageA, params: { msg: B 传回的隐私消息 } })A 接收 paramsthis.$route.params.msg方案3复杂数据 —— 全局状态管理Vuex/Pinia适用传递对象、数组、大量数据或多个页面共享数据。存数据B 页面// Vuex this.$store.commit(SET_MSG, B传给A的数据) // Pinia this.store.msg B传给A的数据跳回 Athis.$router.push(/)A 页面取数据computed: { msgFromB() { // Vuex return this.$store.state.msg // Pinia // return this.store.msg } }三、关键知识点必看1.$router和$route的区别•$router路由实例用来跳转页面push/go/back•$route当前路由信息用来获取参数query/params2.query 和 params 区别方式URL 显示数据类型刷新页面query显示?msgxxx字符串参数保留params不显示任意参数丢失3.A 页面必须监听$route因为 Vue 页面复用不监听路由变化无法实时拿到回传参数。四、最简完整代码直接复制可用PageA.vuetemplate div h1A 页面/h1 p{{ msg }}/p button clickgoToB去 B 页面/button /div /template script export default { data() { return { msg: } }, watch: { $route: getMsg }, mounted() { this.getMsg() }, methods: { goToB() { this.$router.push(/pageB) }, getMsg() { if (this.$route.query.msg) { this.msg this.$route.query.msg } } } } /scriptPageB.vuetemplate div h1B 页面/h1 button clickbackToA返回 A 并传消息/button /div /template script export default { methods: { backToA() { this.$router.push({ path: /, query: { msg: ✅ 我是从B页面带回来的消息 } }) } } } /script总结1.简单数据→ 用query传参最方便、永不丢失2.隐私数据→ 用params传参3.复杂对象→ 用Vuex/Pinia4. A 页面必须监听$route才能实时获取回传参数