在Vue 3中,路由傳參主要通過vue-router實(shí)現(xiàn)。以下是兩種常見的路由傳參方式:
使用路由的params屬性進(jìn)行傳遞。這適用于需要在URL中始終可見的參數(shù)。
// 定義路由時指定參數(shù)
const routes = [
{ path: '/user/:id', component: User }
]
// 導(dǎo)航到一個路由,并傳遞參數(shù)
this.$router.push({ name: 'User', params: { id: 123 }})
// 在User組件中接收參數(shù)
export default {
props: ['id'],
mounted() {
console.log('User ID:', this.id)
}
}
使用路由的query屬性進(jìn)行傳遞。這適用于不需要在URL中可見,但需要在路由間共享的參數(shù)。
// 導(dǎo)航到一個路由,并傳遞查詢參數(shù)
this.$router.push({ path: '/search', query: { keyword: 'Vue3' }})
// 在Search組件中接收參數(shù)
export default {
mounted() {
console.log('Search Keyword:', this.$route.query.keyword)
}
}
在路由定義時,可以通過:paramName語法來定義參數(shù),然后在組件中通過this.$route.params.paramName來獲取。對于查詢參數(shù),可以通過this.$route.query.queryName來獲取。