vue-router传参

80324291 2019-12-10

本文介绍利用props传参,传参的形式有三种:布尔模式、对象模式、函数模式

<router-link :to="{name:‘children‘,params:{id:msg}}">切换咯</router-link>

布尔模式将props属性设置成为true,如果 props 被设置为 trueroute.params 将会被设置为组件属性。

{
        path: ‘/index‘,
        component:() => import(‘../src/components/index/index.vue‘), 
        children: [{
            path: ‘/children/:id‘,
            name:‘children‘,
            component:() => import(‘../src/components/index/children/index.vue‘),
            props: true,  //关键代码
        }]
    },//index/children.vueexport default{  props:[‘id‘]}

对象模式在路由配置(router.js)里边设置props为对象{id:”msg”},然后去组件中设置props,props的值为路由配置里边的props的key,也就是id

{
        path: ‘/index‘,
        component:() => import(‘../src/components/index/index.vue‘), 
        children: [{
            path: ‘/children‘,
            name:‘children‘,
            component:() => import(‘../src/components/index/children/index.vue‘),
            props: {
                id:‘msg‘
            },
        }]
    },

注意:这样设置只使用与props里面的值是静态的

函数模式可以创建一个函数返回 props。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等

{
        path: ‘/index‘,
        component:() => import(‘../src/components/index/index.vue‘), 
        children: [{
            path: ‘/children‘,
            name:‘children‘,
            component:() => import(‘../src/components/index/children/index.vue‘),
            props:()=>({id:‘msg1‘}),  //静态设置
        }]
    },
{
        path: ‘/index‘,
        component:() => import(‘../src/components/index/index.vue‘), 
        children: [{
            path: ‘/children‘,
            name:‘children‘,
            component:() => import(‘../src/components/index/children/index.vue‘),
            props:(route)=>({id:route.params.id}),  //动态设置
        }]
    },

相关推荐