Vue路由组件的传值

268 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第一天,点击查看活动详情

前言

(ง •_•)ง 最近学习了Vue的路由组件间的传参,苦于自己记忆力有限,故写下此篇文章记录下学习的成果

准备

1.下载Vue-router并创建文件夹router及配置文件

npm install vue-router --save

2.在main.js中导入文件并使用

//引入VueRouter
import VueRouter from 'vue-router'
//引入路由器
import router from './router'

3.编写配置文件

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import Aboutus from '../components/Aboutus'
import Home from '../components/Home'
import Student from '../components/Student'
import School from '../components/School'


//创建并暴露一个路由器
export default new VueRouter({
    routes: [
        {
            name:"aboutus",
            path: '/aboutus',
            component: Aboutus
        },
        {
            name: "home",
            path: '/home',
            component: Home,
            children:[
                {
                    name: "school",
                    path: '/school',
                    component: School
                }, 
                {
                    name: "student",
                    path: '/student',
                    component: Student
                },
            ]
        }
    ]
})

两个路由组件的传值

首先搭建页面

image.png 现在假设Home中有这样一组数据要传到School组件中显示

image.png 我们应该想要有这样的结果,那么该如何解决呢?

image.png

有两种方式,一种是通过路由的query参数传参,第二种是路由的params参数

路由的query参数传参(类似于axios通过query参数发送请求)

<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link :to="/home/school/?id=1&name=王城二小"></router-link>
				
<!-- 跳转并携带query参数,to的对象写法 -->
<router-link 
	:to="{
		path:'/home/school',
		query:{
		   id:1,
                   name:'王城二小'
		}
	}"
></router-link>

接收参数

$route.query.id
$route.query.title

知道了这种方法,我们就可以开始传参了,并且在控制台打印this.$route看看有没有成功,

(注意数组要先用JSON.stringify转为字符串,school页面要先在计算属性中用JSON.parse(this.$route.query.xxx)接收参数)

image.png

image.png

image.png

路由的params参数传参(类似于axios通过params参数发送请求),这里不再传数组,传单个数据

在router的配置文件中

export default new VueRouter({
    routes: [
        {
            name:"aboutus",
            path: '/aboutus',
            component: Aboutus
        },
        {
            name: "home",
            path: '/home',
            component: Home,
            children:[
                {
                    name: "school",
                    path: '/school/:id/:name',
                    component: School
                }, 
                {
                    name: "student",
                    path: '/student',
                    component: Student
                },
            ]
        }
    ]
})

传递参数

<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/home/school/id/name">跳转</router-link>
                
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link 
    :to="{
        name:'school',
        params:{
           id:1,
           name:'王城二小'
        }
    }"
>跳转</router-link>

特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置! 接收参数

```
$route.params.id
$route.params.name
```

传值成功

image.png 这里就是全部内容了,我们下期再见!