天天看點

深入簡出vue路由——5.路由元件傳參

在元件中使用 $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>