在router目录下的index.js文件中,对path属性加上/:id。
使用router对象的params.id 例如 : this.$route.params.id
详解:https://blog.csdn.net/weixin_41399785/article/details/79381357
路由的定义,主要有以下几步:
-
如果是模块化机制,需要调用 Vue.use(VueRouter)
-
定义路由组件,如:
const Foo = { template: '<div>foo</div>' };
- 1
- 2
- 3
-
定义路由(数组):
const routes = [ { path: '/foo', component: Foo } ];
- 1
- 2
- 3
- 4
- 5
- 6
-
创建 router 实例
const router = new VueRouter({ routes });
- 1
- 2
- 3
-
创建和挂载根实例
const app = new Vue({ routes }).mount('#app');
- 1
- 2
- 3
嵌套路由主要是通过 children,它同样是一个数组:
{ path: '/user', component: User, children: [ { path: 'file', component: File } ] }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
这时访问,/user/file 会映射到 File 组件
动态路由的创建,主要是使用 path 属性过程中,使用动态路径参数,以冒号开头,如:
{ path: /user/:id component: User }
- 1
- 2
- 3
- 4
这会是访问 user 目录下的所有文件,如 /user/a 和 /user/b,都会映射到 User 组件
当匹配到 /user 下的任意路由时,参数值会被设置到 this.$route.params 下,所以通过这个属性可以获取到动态参数,如:
const User = { template: '<div>User {{ $route.params.id }}</div>' }
- 1
- 2
- 3
这里会根据访问的路径动态的呈现,如访问 /user/aaa 会渲染:
<div> User aaa </div>