Vue路由传参详解(params 与 query)
1.通过params传参
params传参需要配合路由中name(name是什么呢?name 是配置路由时给 path 取的别名,)
- 编程式:
<button @click="add">nav</button>
methods: {
add () {
//params传参需要配合name来进行
this.$router.push({ name: 'nav', params: { name: 'zhang', id: 999 } })
}
}
- 声明式:
router-link跳转页面,如果携带参数,to可以绑定一个对象
to对象有两个属性:name,要跳转的路径的别名;params属性,需要传输的参数
<router-link :to="{ name: '/about', params: { name: 'zhang',id:999 } }">About</router-link>
- 接受参数:
created () {
const res = this.$route.params // 接受参数
console.log(res, 222) // {name: 'zhang', id: 999}
}
2.通过query传参
query传参可以配合路由中name和path, 地址栏会把传入参数添加在url后面
- 编程式:
使用编程式传参,html里面标签不能为router-link,得为其他标签比如(a,button,p)
<button @click="add">nav</button>
methods: {
add () {
this.$router.push({ path: '/nav', query: { name: 'zhang', id: 999 } })
}
}
- 声明式:
<router-link :to="{ path: '/about', query: { name: 'jack',id:999 } }"
>About</router-link
>
- 接受参数: 使用this.$route.query来接收
created () {
const res = this.$route.query // 接受参数
console.log(res, 222) // {name: 'zhang', id: 999}
}