Vue路由传参方法详解_this_缺点需要在路由配置中显式启用适用范围有限
Vue路由传参方法详解
一、路径参数(params)传参
在定义路由时,可以在路径中添加冒号来定义路径参数。例如:```
``` this.$router.push({ name: 'user', params: { id: 123 } }); ``` 在组件中获取参数,通过`this.$route.params`访问。例如:
``` export default { created() { console.log(this.$route.params.id); // 输出:123 } } ``` 优点:URL清晰,适合标识资源场景。
缺点:路径参数只能传递字符串类型的值。
二、查询参数(query)传参
定义路由时无需特别设置,查询参数直接附加在路径后面。例如:```
``` this.$router.push({ name: 'user', query: { id: 123 } }); ``` 在组件中获取参数,通过`this.$route.query`访问。例如:
``` export default { created() { console.log(this.$route.query.id); // 输出:123 } } ``` 优点:适合传递多个参数,参数类型不受限。
缺点:URL可能变得较长且不够美观。
三、通过props传参
在路由配置中启用`props`:例如:``` { path: '/user/:id', name: 'user', component: User, props: true } ``` 在导航时传递参数,与路径参数类似。例如:
``` this.$router.push({ name: 'user', params: { id: 123 } }); ``` 在组件中获取参数,通过`props`接收。例如:
``` export default { props: ['id'], created() { console.log(this.id); // 输出:123 } } ``` 优点:参数直接作为组件的`props`,使用更方便。
缺点:需要在路由配置中显式启用,适用范围有限。