11.1 参数的传递
对于 router 路由来说,router-link
是可以传参的。而且 有两种 方式,可以拿到 这个传递过去的参数。
- 不开启 props 的方式
router-link
的属性 to 其实 是可以 写成 v-bind:to
的。
只不过 一旦写成了 v-bind:to
就只能 依靠 路由配置的 name
来确定 跳转的 组件 是谁了。但是它能传参!!!
<router-link v-bind:to = "{name: 'UserProFile', params: {id: 1}}">个人信息</router-link>
然后 把 路由配置 那里的 path 改动一下,拼接一下 待传递过来的参数名。以 /:参数名
的格式。
children: [
{
name: 'UserProFile',
path: "/user/profile/:id",
component: Profile
},
this.$route.params.id 就可以 直接 拿到 传递过来的 那个 id
<template>
<div>
<h1>{{this.$route.params.id}}</h1>
</div>
</template>
<script>
export default {
name: "Profile"
}
</script>
<style scoped>
</style>
- 开启 props 的形式
如果开启了 props,这样的话 就可以 解耦了。就是我们 从 跳转到的 那个 组件,props 里面 拿到这个 id。在 路由 配置那里 写 上 props:true
就完事了。
import Vue from 'vue'
import Router from 'vue-router'
import Main from '../views/Main'
import Login from "../views/Login";
import Profile from "../views/user/Profile";
import List from "../views/user/List";
Vue.use(Router);
export default new Router({
routes: [
{
name: 'main',
path: '/main',
component: Main,
children: [
{
name: 'UserProFile',
path: "/user/profile/:id",
props: true, // 开启 props
component: Profile
},
{
path: "/user/list",
component: List
}
]
},{
name: 'login',
path: '/login',
component: Login
}
]
});
<template>
<div>
<h1>{{id}}</h1>
</div>
</template>
<script>
export default {
name: "Profile",
props: ['id']
}
</script>
<style scoped>
</style>
11.2 重定向
重定向 其实 还是 挺容易的。如果 你不想实现什么 花活的话。
就是 在 路由配置 那里,写上 redirect: 其它的路由地址