1. 查询字符串
// 传参
this.$router.push(`/home?id=${99}`)
// 接收使用参数
this.$route.query.id // this.$route.query 是一个对象
传递多个数据,对象类型
// name 则是路由规则里面对应的name
this.$router.push({name:'Home',query:{id:1,pid:10}})
// 查询字符串方式 可以用 path或者name
this.$router.push({path:'Home',query:{id:1,pid:10}})
2. 动态参数
// 定义变量
export default {
name: 'Home',
data () {
return {
num: 10
}
}
}
----------------------------------
this.$router.push('/home/'+num) // 传参
// 动态参数的方式, 要在router的path中配置
{
path: '/home/:id',
name: 'home',
component: Home
},
传递多个数据,对象类型
// 通过动态参数,params传参,如果传是以对象方式, 只能使用 name
this.$router.push({ name: 'son', params: { id: 123, age: 199 } })
vue3 的传参方式
使用vue3的方式,同时也支持vue2的写法
<template>
<div class="home">
父组件
<button @click="push1">跳转传参</button>
</div>
</template>
<script>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
export default {
name: 'Home',
data () {
return {
num: 10
}
},
setup () {
const num = ref(10)
const router = useRouter()
const push1 = () => {
router.push('/son/' + num.value)
}
return {
push1
}
}
}
</script>