基本语法:
valueString PS:上面to前边是带冒号,后边跟的是一个对象形势的字符串
name:在路由配置文件中起的name值。叫做命名路由,下一节会讲到。 params:要传的参数,它是对象形式,在对象里可以传递多个值。 具体实例如下: (1)在src/components/Home.vue里面导航中添加如下代码:
<router-link :to="{name: 'one', params:{username:'test123'}}">子页面1</router-link>(2)在src/router/indes.js中添加如下代码,重点是name:
{ path:'one', // 子页面1 name: 'one', // 路由名称-命名路由 component:One } (3)在src/components/One.vue里面接受参数,代码如下: <h2>{{$route.params.username}}</h2>(1)在路由中以冒号传递,在src/router/index.js中加入如下代码:
{ path:'/home/two/:id/:name', // 子页面2 component:Two },(2)接受参数,在src/components/Two.vuez中加入如下代码:
<p>ID:{{ $route.params.id}}</p> <p>名称:{{ $route.params.name}}</p> (3)路由跳转,在src/components/Home.vue中加入如下代码: <router-link to="/home/two/1/张三">子页面2</router-link>PS:to前没有冒号为字符串路由,必须全部匹配。 (4)如果路由参数需要有特定的规则,就需要加入正则表达式了,示例如下:
{ path:'/home/two/:id(\\d+)/:name', // 子页面2 component:Two }(1)在src/router/index.js页面加入如下代码:
{ path:'/home/three', // 子页面3 name: 'three', component:Three }(2)在src/components/Three.vue页面加入如下代码:
<p>ID:{{ $route.params.id}}</p> <p>名称:{{ $route.params.name}}</p>(3)在src/components/Home.vue中加入如下代码:
// template <button @click="toThreePage">页面3-params传参</button> // script methods: { toThreePage() { this.$router.push({name: 'three', params: {id: 1, name: 'zhangsan'}}) } }说明: A、动态路由使用params传递参数,在this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面。 B、以上方式参数不会显示到浏览器的地址栏中,如果刷新一次页面,就获取不到参数了,改进方式将第一部中的代码改成如下:
{ path:'/home/three/:id/:name', // 子页面3 name: 'three', component:Three }(1)在src/router/index.js页面加入如下代码:
{ path:'/home/three', // 子页面3 name: 'three', component:Three }(2)在src/components/Three.vue页面加入如下代码:
<p>ID:{{ $route.query.id}}</p> <p>名称:{{ $route.query.name}}</p> (3)在src/components/Home.vue中加入如下代码: // template <button @click="toThreePage">页面3-params传参</button> // script methods: { toThreePage() { this.$router.push({path: '/home/three', query: {id: 1, name: 'zhangsan'}}) } }PS:动态路由使用query传递参数,会显示到浏览器地址栏中,以上链接为 /home/three?id=1&name=zhangsan