VueJS 3组合式API+script setup中如何传递对象给路由?
Vue路由传递对象的简便解决方案
方法1:序列化对象为query参数
把对象转成JSON字符串通过query参数传递,接收时再解析还原,无需修改路由配置的path。
跳转时的代码:
// 跳转路由前序列化user对象 this.$router.push({ path: '/home', query: { user: JSON.stringify(this.user) } })
路由配置保持简单:
{ path: '/home', component: Home }
在Home组件中接收并解析:
mounted() { const userStr = this.$route.query.user if (userStr) { this.user = JSON.parse(userStr) } }
注意:query参数会明文显示在URL中,不适合传递敏感数据。
方法2:用状态管理(Vuex/Pinia)存储对象
将对象存入全局状态管理容器,跳转路由后直接从容器中读取,完全不需要在路由参数里传递。
以Pinia(Vue3推荐)为例:
- 定义状态仓库:
// store/userStore.js import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ currentUser: null }), actions: { setUser(user) { this.currentUser = user } } })
- 跳转前存储对象:
import { useUserStore } from '@/store/userStore' const userStore = useUserStore() // 先把user存入状态管理 userStore.setUser(this.user) // 再跳转到/home路由 this.$router.push('/home')
- 在Home组件中读取:
import { useUserStore } from '@/store/userStore' const userStore = useUserStore() mounted() { this.user = userStore.currentUser }
这种方式不会在URL中暴露数据,适合传递复杂或敏感对象。
方法3:临时使用Vue实例全局属性(不推荐)
如果是简单临时场景,也可以把对象挂载到Vue实例的全局属性上(Vue2用Vue.prototype.$tempUser,Vue3用app.config.globalProperties.$tempUser),但这种方式容易造成全局污染,仅适合临时应急场景。
内容的提问来源于stack exchange,提问作者user22453190
相关产品推荐
相关产品推荐

