params 传参
router.js
...
{
path: "/user/:id", // path后面要加上参数
name: "user", // name是必须的
component: () => import("../views/User") //懒加载组件
}
...
User.vue
//组件中
<router-link to="/user/123"> 跳转</router-link>
<router-link :to="{ name: 'user', params: { id: 123 }}"> 跳转</router-link>
//点击事件中
this.$router.push({
name: "user",
params: {
id: '123' //id的值
}
});
点击后路由效果为:
http://localhost:8080/#/user/123
页面中获取参数
this.$route.params.id
跳转时候的值
router.beforeEach((to, from, next) => {
console.log(to.fullPath) // '/user/123'
console.log(to.path) // '/user/123'
})
query传参
router.js
...
{
path: "user",
component: () => import("../views/User") //懒加载组件
}
...
User.vue
//组件中
<router-link :to="{ path:'/user', query: { id: 123} }"> 跳转</router-link>
//点击事件中
this.$router.push({
path: "/user", //要填写完整的路径
query: {
id: 123 //id的值
}
});
点击后路由效果为:
http://localhost:8080/#/user?id=123
页面中获取参数
this.$route.query.id
跳转时候的值
router.beforeEach((to, from, next) => {
console.log(to.fullPath) // '/user?id=123'
console.log(to.path) // '/user'
})