在组件中使用
$route
会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。官方文档给出了使用props
将组件和路由解耦的示例,这里展示一下传统方式和采用props
解耦方式的使用方法。
不采用 props 让组件和路由解耦
1. query
传递的参数拼接在 url 上,例如:
/home?id=1
-
route-link:
父组件:<router-link to="/comp?msg='comp’s query'"> comp </router-link>
路由组件接收参数:$route.query
-
编程式:
父组件:router.push({ path: 'comp', query: { msg: 'comp’s query'}})
路由组件接收参数:$route.query.msg
2. params
动态路由匹配,或者编程式传递 params 参数
-
route-link:
父组件:<router-link to="/comp/123"> comp </router-link>
。
同时需要在路由文件中定义:
{
path: '/comp/:id',
component: xxxx,
}
路由组件接收参数:$route.params.id
-
编程式:
父组件:router.push({ name: 'comp', params: { id: 123}})
同时需要在路由文件中定义name
属性:
{
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>
网友评论