vue实现页面传参
路由传参(动态路由)
在路由配置中定义动态参数,通过this.$route.params获取参数。
路由配置示例:
{
path: '/user/:id',
component: User
}
跳转时传参:
this.$router.push('/user/123')
接收参数:
const userId = this.$route.params.id
query传参
通过URL的查询字符串传递参数,使用this.$route.query获取。
跳转时传参:
this.$router.push({
path: '/user',
query: {
name: 'John',
age: 30
}
})
接收参数:
const name = this.$route.query.name
const age = this.$route.query.age
props传参
将路由参数作为组件的props传递,需要在路由配置中开启props。
路由配置:
{
path: '/user/:id',
component: User,
props: true
}
组件接收:
export default {
props: ['id']
}
编程式导航传参
使用this.$router.push的state参数传递对象(Vue Router 4+)。
跳转时传参:
this.$router.push({
name: 'User',
state: {
userInfo: {
name: 'Alice',
age: 25
}
}
})
接收参数:
const userInfo = history.state.userInfo
事件总线传参
创建全局事件总线实现任意组件间通信。
创建事件总线:
// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
发送参数:
import { EventBus } from './eventBus'
EventBus.$emit('updateUser', { name: 'Tom' })
接收参数:
import { EventBus } from './eventBus'
EventBus.$on('updateUser', (data) => {
console.log(data.name)
})
Vuex状态管理
通过全局状态管理实现跨组件数据共享。
store定义:
const store = new Vuex.Store({
state: {
user: null
},
mutations: {
setUser(state, payload) {
state.user = payload
}
}
})
提交数据:
this.$store.commit('setUser', { name: 'Lisa' })
获取数据:
const user = this.$store.state.user
localStorage/sessionStorage
通过浏览器本地存储实现页面间数据持久化传递。
存储数据:
localStorage.setItem('userToken', 'abc123')
获取数据:
const token = localStorage.getItem('userToken')
移除数据:
localStorage.removeItem('userToken')






