vue-router 路由基础的详解(2)

JS:

const User = {
   template:'<div><p>我的ID是{{ $route.params.id }}</p><router-link to="/user/childone">ChildOne</router-link><router-link to="/user/childtwo">ChildOne</router-link><router-view></router-view></div>',
   }

   // 子路由
   const userChildOne = {
    template:'<div>我是 userChildOne</div>'
   }
   const userChildTwo = {
    template:'<div>我是 userChildTwo</div>'
   }
  const router = new VueRouter({
   routes:[
     {path:'/user/:id',component:User,
      children:[ // 用法和参数和routes 一样
       {path:"/user/childone",component:userChildOne},
       {path:"/user/childtwo",component:userChildTwo}
      ]

     }
   ]
  });

  var myVue = new Vue({
    router
  }).$mount("#myDiv")

四、命名路由

1.给路由命名指定路路由跳转,要用到参数name 和 v-bind

HTML:

<div id="myDiv">
<!-- 要用v-bind 的绑定to -->
 <router-link :to="{name:'userOne',params:{userId:'123'}}">Go to foo</router-link> 
 <router-link :to="{name:'userTwo',params:{userId:'456'}}">Go to bar</router-link> 

  <router-view></router-view>
</div> 

JS:

const User = {
   template:'<p>我的ID是{{ $route.params.userId }}</p>',
   watch:{
    '$route'(to,form){
     console.log(to);
     console.log(form);
    }
   }
  }

  const router = new VueRouter({
   routes:[
   // name 一一对应上
     {path:'/user/:userId',name:"userOne",component:User},
     {path:'/user/:userId',name:"userTwo",component:User}
   ]
  });

  var myVue = new Vue({
    router
  }).$mount("#myDiv")

五、命名视图

1.给渲染视图 router-view 命名,来制定让那个视图渲染组件

HTML:

<div id="myDiv">
<!-- 要用v-bind 的绑定to -->
 <router-link :to="{name:'userOne',params:{userId:'123'}}">Go to foo</router-link> 
 <router-link :to="{name:'userTwo',params:{userId:'456'}}">Go to bar</router-link> 
<!-- 视图命名 如果不写name 则为默认为 default-->
  <router-view></router-view>
  <router-view name='b'></router-view>
</div> 

JS:

// 四个模板
  const UserA = {
   template:'<p>我是one,ID是{{ $route.params.userId }}</p>',
  }
  const UserB = {
   template:'<p>我是two,ID是{{ $route.params.userId }}</p>',
  }
  const UserC = {
   template:'<p>我是three,ID是{{ <1ro></1ro>ute.params.userId }}</p>',
  }
  const UserD = {
   template:'<p>我是four,ID是{{ $route.params.userId }}</p>',
  }
  const router = new VueRouter({
   routes:[
   // name 一一对应上
     { 
      path:'/user/:userId',
      name:"userOne",
      components:{ // 注意这里为components 多个“ s ”
        default:UserA,
        b:UserB
      }
     },
     { 
      path:'/user/:userId',
      name:"userTwo",
      components:{
        default:UserD,
        b:UserC
      }
    }
   ]
  });

  var myVue = new Vue({
    router
  }).$mount("#myDiv")


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6079.html