Vue 基础【2】— 路由间传参

2020-10-15  本文已影响0人  弱冠而不立

在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。官方文档给出了使用 props 将组件和路由解耦的示例,这里展示一下传统方式和采用 props 解耦方式的使用方法。

不采用 props 让组件和路由解耦

1. query

传递的参数拼接在 url 上,例如: /home?id=1

2. params

动态路由匹配,或者编程式传递 params 参数

{   
        path: '/comp/:id', 
        component: xxxx,
}

路由组件接收参数:$route.params.id

 {   
        path: '/comp/:id', 
        component: xxxx,
        name: comp
 },

路由组件接收参数:$route.params.msg

注意: 若在编程式跳转路由时是router.push({ path: 'comp', params: { id: 123}}) 则这里的 params 不生效

采用 props 让组件和路由解耦

  // router/index.js
 {   
        path: 'comp1/:id', 
        component: () => import("../components/router-props/Comp1.vue"),
        name: "comp1",
        props: true,
},
<!--  父组件 -->
<router-link to="/vue_router/comp1/1">Comp1</router-link>
<!-- Comp1 组件 -->
<template>
  <div>
    <h3>这是 Comp1,id为:{{ id }}</h3>
    <!-- 这是 Comp1,id为:1 -->
  </div>
</template>

<script>
export default {
  name: "Comp1",
  props:["id"],
}
</script>
//如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。
{   
        path: 'comp2', 
        component: () => import("../components/router-props/Comp2.vue"),
        name: "comp2",
        props: {
             id: 2,
             msg: "It is Comp2"
        },
}
<!-- 父组件 -->
<router-link to="/vue_router/comp2?id=123">Comp2</router-link>
<!-- Comp2 组件 -->
<template>
    <div>
        <h1>Comp2</h1>
        <h3>id: {{id}}</h3>
        <!-- id: 2 -->
        <h3>msg: {{msg}}</h3>
        <!-- msg: It is Comp2 -->
    </div>
</template>

<script>
export default {
    name: "Comp2",
    props: ["id", "msg"]
}
</script>
//可以将参数转换成另一种类型,将静态值与基于路由的值结合
 {
       path: 'comp3', 
       component: () => import("../components/router-props/Comp3.vue"),
       name: "comp3",
       props: (route) => ({ 
            msg: "hello " + route.query.msg,
       })
},
  // 父组件函数式跳转
 goToComp3() {
      this.$router.push({path: "/vue_router/comp3?msg=world"})
    },
<!-- Comp3 组件 -->
<template>
    <div>
        <h3>msg: {{msg}}</h3>
        <!-- msg: hello world -->
    </div>
</template>

<script>
export default {
    name: "Comp3",
    props: ["msg"]
}
</script>
上一篇 下一篇

猜你喜欢

热点阅读