vue2、vue3路由的props配置

148 阅读1分钟

不管是vue2还是vue3,路由的props传参有三种方式:

1.props设置为true

{
        name:'About',
        path:'/about/:a/:b/:c',
        component:()=>import('@/pages/about/index.vue'),
        meta:{
            title:'about'
        },
        props:true
    },
    
    <RouterLink  to="/about/呵呵/哈哈/嘎嘎"  active-class="active">
            <el-button type="primary">about</el-button>
            <!-- :to="{name:'About',params:{a:'哈哈',b:'呵呵',c:'嘎嘎'}}" -->
        </RouterLink>
        /*或者*/
        <RouterLink  :to="{name:'About',params:{a:'哈哈',b:'呵呵',c:'嘎嘎'}}"  active-class="active">
            <el-button type="primary">about</el-button>
        </RouterLink>

这种方式只能实现params传参

2.通过函数的方式返回一个对象

    {
        name:'About',
        path:'/about',
        component:()=>import('@/pages/about/index.vue'),
        meta:{
            title:'about'
        },
        // props:true
        props:(route)=>{
            return route.params
        }
    },

不仅可以实现params传参,还可以实现query传参

    {
        name:'About',
        path:'/about',
        component:()=>import('@/pages/about/index.vue'),
        meta:{
            title:'about'
        },
        // props:true
        props:(route)=>{
            return route.query
        }
    },

3.传递对象

一般这种方式很少用,因为这种方式传递参数在路由写死,在实际开发中意义不大,不过也给大家介绍一下

    {
        name:'About',
        path:'/about',
        component:()=>import('@/pages/about/index.vue'),
        meta:{
            title:'about'
        },
        // props:true
        props:{
        a:"哈哈",
        b:"嘎嘎",
        c:"呵呵"
        }
    },

一般路由传参我们使用params、query传参,vue2中通过this.route.params或者this.route.params或者this.route.query获取参数,在vue3中我们可以

import {useRoute} from 'vue-router'
let route = useRoute()
route.params
route.query

这种方式使用起来也可以,但是通过路由的props配置,可以直接实现props传参,接收参数使用起来更方便

Snipaste_2024-08-03_23-17-57.png