Vue页面、组件之间传参方式繁多,此处罗列出常用的几种方式,欢迎审阅补充。
这里的路由传参以编程式 router.push(...)
为例,声明式 <router-link :to="...">
与之类似。此处模拟情景为从 componentsA.vue
页面跳转到 componentsB.vue
页面传参。首先,路由配置信息如下:
router.js
import Vue from 'vue'import Router from 'vue-router'import componentsA from './components/componentsA' //在components下创建componentsA.vueimport componentsB from './components/componentsB' //在components下创建componentsB.vueVue.use(Router)export default new Router({ routes:[ { path:'/componentsA', name:'componentsA', component:componentsA }, { path:'/componentsB', name:'componentsB', component:componentsB } ]})
1.1 路由配置传参
首先确定自己要传的参数名,将路由配置修改一下,传name,age,sex三个参数:
{ path:'/componentsB/:name/:age/:sex', name:'componentsB', component:componentsB }
在 componentsA.vue
页面通过 this.$router.push
配置与之对应的参数:
componentsA.vue
<template> <div> <div>我是组件A</div> <button @click='routerToB1'>方式一跳转到组件B</button> </div></template><script> export default{ data(){ return{ person:{name:'Gene',age:'18',sex:'male'} } }, methods: { routerToB1() { this.$router.push({ path:`componentsB/${this.person.name}/${this.person.age}/${this.person.sex}` }) } }, }</script><style></style>
然后在 componentsB.vue
页面用 this.$route.params
接收参数:
componentsB.vue
<template> <div> <div>我是组件B</div> </div></template><script> export default{ created(){ this.getRouterData() }, methods: { getRouterData(){ const param = this.$route.params console.log(param)//{name:'Gene',age:'18',sex:'male'} } }, }</script><style></style>
点击按钮"方式一跳转到组件B",componentsB页面打印出 {name:'Gene',age:'18',sex:'male'}
,成功获取到A页面传过来的参数,并且地址栏显示为 localhost:8889/#/componentsB/Gene/18/male
(端口号根据自己设置的来),表明这种传参方式url会携带参数。
1.2 params传参
首先将刚才路由配置修改部分还原,在 componentsA.vue
页面添加按钮"方式二跳转到组件B":
componentsA.vue
<template> <div> <div>我是组件A</div> <button @click='routerToB1'>方式一跳转到组件B</button> <button @click='routerToB2'>方式二跳转到组件B</button> </div></template>
新闻热点
疑难解答
图片精选