1.参数传递
这里演示如果请求带有参数该怎么传递
- 用的还是上述例子的代码 修改一些代码 这里不放重复的代码了
第一种取值方式
1、 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符
- name: ‘UserProfile’
{
path: '/user/profile/:id',
name: 'UserProfile',
component: UserProfile
},
2、传递参数
此时我们在Main.vue中的route-link位置处 to 改为了 :to(如果要传参数的话就需要用v-bind:来绑定),是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;
- 前面属性没写name是因为只有一个属性
<el-menu-item index="1-1">
<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name: 'UserProfile', params: {id: 1}}">个人信息</router-link>
</el-menu-item>
3、在要展示的组件Profile.vue中接收参数 使用 {{$route.params.id}}来接收
Profile.vue 部分代码
- 所有元素必须在根节点下
<div></div>
<template>
<div>
<!-- 所有的元素必须在根节点下-->
<h1>个人信息</h1>
{{$route.params.id}}
</div>
</template>
第二种取值方式 使用props 减少耦合【推荐】
1、修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性
{
path: '/user/profile/:id',
name: 'UserProfile',
component: UserProfile,
props: true
},
2、传递参数和之前一样 在Main.vue中修改route-link地址
<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>
3、在Profile.vue接收参数为目标组件增加 props 属性
Profile.vue
<template>
<div>
<!-- 所有的元素必须在根节点下-->
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile"
}
</script>
<style scoped>
</style>
2.组件重定向
- 重定向:从一个页面跳转到另一个页面
- url不变的跳转叫做转发
1、重定向的意思大家都明白,但 Vue 中的重定向是作用在路径不同但组件相同的情况下,比如:在router下面index.js的配置
- 说明:这里定义了两个路径,一个是 /main ,一个是 /goHome,其中 /goHome 重定向到了 /main 路径,由此可以看出重定向不需要定义组件;
{
path: '/main',
name: 'Main',
component: Main
},
{
path: '/goHome',
redirect: '/main'
}
2、使用的话,只需要在Main.vue设置对应路径即可;
3、结果: