vue工作开发总结(一)---- 路由参数解耦

一般在组件内使用路由参数,大多数人会这样做:

export default{
    methods:{
        getParamsId(){
            return this.$route.params.id
        }
}

在组件中使用$route会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的url上使用,限制了他的灵活性

 

正确的做法应该是使用props解耦:

const router =new VueRouter({
    routes:[{
        path:"user/:id",
        component:User,
        props:true
    }]
})
这样将路由props属性设置为true后,组件内可以通过props接受到params参数

export default {
    props:['id'],
    methods:{
        getParamsId(){
            return this.id
        }
    }
}

宁外还可以通过函数模式来返回props
const router = new VueRouter({
    routes:[{
        path:'user/:id',
        component:User,
        props:(route)=>({
            id:route.query.id
        })
    }]
})

 

文档查看地址:https://router.vuejs.org/zh/guide/essentials/passing-props.html

你可能感兴趣的:(vue)