在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。
使用 props 将组件和路由解耦:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link>
<router-link to="/user/boo/kkk">/user/foo/kkk</router-link>
<router-link to="/user/boo/qqq">/user/foo/qqq</router-link>
</p>
<router-view></router-view>
</div>
<script type="text/javascript">
const User = {
props:['id'],
template:`
<div class="user">
<h2>User {{id}}</h2>
<router-view></router-view>
</div>
`
}
const ccc = {
template:'<h3>CCC</h3>'
};
const kkk = {
template:'<h3>KKK</h3>'
};
const qqq = {
template:'<h3>QQQ</h3>'
}
const router = new VueRouter({
routes:[
{
path:'/user/:id',// 动态路径参数 以冒号开头
component:User,
props: true, //通过 props 解耦
children:[
{path:'',component:ccc},
{path:'kkk',component:kkk},
{path:'qqq',component:qqq}
]
}
]
})
const app = new Vue({
router//ES6解构函数的写法相当于 router:router
}).$mount('#app')
</script>
</body>
</html>