Vue Router传值的方法
vue路由传值共有两种方式:1.
query
2.params
query
-
使用
query
传参,路由配置时path不用带参数//路由配置 { name: 'detail', path: '/detail', component: Detail } // 使用: // 使用name引入路由(三种方式效果相同) 1. <router-link :to="{name: 'detail',query:{ id:123 }}">点击</router-link> 2. this.$router.push({name: 'detail',query:{ id:123 }}) 3. this.$router.push('/detail?id=${this.$route.query.id}') // 使用path引入路由(两种方式效果相同) 1. <router-link :to="{path: 'detail',query:{ id:123 }}">点击</router-link> 2. this.$router.push({path: 'detail',query:{ id:123 }}) // 页面显示的结果:http://localhost:8080/#/detail?id=123
-
获取参数值的方法
this.$route.query.id
params
-
路由配置时,path需要带参数
// 路由配置 { name: 'detail', path: '/detail/:id',// 这里需要带参数 component: Detail } // 使用: // 只能使用name引入路由(三种方式效果相同) 1. <router-link :to="{name: 'detail', params:{ id:123 }}">点击</router-link> 2. this.$router.push({name: 'detail', params:{ id:123 }}) 3. this.$router.push('/detail/${this.$route.params.id}') // 页面显示结果:http://localhost:8080/#/detail/123
-
获取参数值的方法
this.$route.params.id
两者的区别
- 路由配置不同
- query传值: 使用query传参,路由配置时path不用带参数
path: '/detail'
- param传值: 路由配置时,path需要带参数
path: '/detail/:id'
- query传值: 使用query传参,路由配置时path不用带参数
- 使用时条件限制不同
- query传值:
query
可以和name
或path
一起使用 - param传值:
params
不能与path
一起使用
- query传值:
- 页面显示结果不同
- query传值: 页面显示的结果:
http://localhost:8080/#/detail?id=123
- param传值: 页面显示结果:
http://localhost:8080/#/detail/123
- query传值: 页面显示的结果: