vue 动态路由,路由嵌套

1.动态路由

我们经常需要把某种匹配模式映射到同一个组件,比如,用户通过输入这样一个url来
进入网址
http://localhost:8080/user/userid,代表要进入用户界面
这样所有的用户只有id不一样,那这时怎么办呢?动态路由匹配

在路由中写:

import User '@/component/User';

var router = new VueRouter({
  routes:[
    {
    //这样的写法就会让user/之后的东西成为id
      path:'/user/:id',
      //也可以设置多个参数,如下
      //   /user/:username/post/:post_id
      compoment : User
    }
  ]
})


//在User的组件里面就可以拿到此参数

this is User comonent , your id is {{$route.params.id}}

2.路由嵌套

比如你已经有了以下路由

var router = new VueRouter({
  routes:[
  //你现在写了一个国家的组件,里面要匹配上省份
    {
      //name和component的不同下面会讲到
      name:'countryName',
      path : '/country/:countryId',
      component:Country,
      children:[
      //当匹配到 /country/:countryId/henan/时匹配到
      //注意,这里的path前面不加‘/’
        {path:'henan' , component: HeNan},
        {path: 'beijing' , component: BeiJing}
      ]
    },
  ]
})

在component的html部分,解释在代码里面(name和component的不同点)

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- 使用 router-link 组件来导航. -->
    <!-- 通过传入 `to` 属性指定链接. -->
    <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
    
     <!-- 如果是使用了name属性,那么可以这样 -->
     <router-link :to="{name:'countryName'}">Go to Bar</router-link>
     
     <!-- 如果要传递参数的话,使用name作为路由就非常方便了 -->
     <router-link :to="{name:'countryName' , params:{ 'a' : 'aa'}}">
    	 Go to countryName
     </router-link>
  </p>
  
  <!-- 上面只是整体写了路由,并且<router-link></router-link>最终会设置为一个超链接
  <!-- 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
</div>
如 \color{#2d85f0}{如} 果 \color{#f4433c}{果} 感 \color{#ffbc32}{感} 觉 \color{#2d85f0}{觉} 写 \color{#0aa858}{写} 的 \color{#f4433c}{的} 还 \color{#2d85f0}{还} 不 \color{#f4433c}{不} 错 \color{#ffbc32}{错} , \color{#2d85f0}{,} 不 \color{#0aa858}{不} 要 \color{#f4433c}{要} 忘 \color{#2d85f0}{忘} 记 \color{#f4433c}{记} 点 赞 \color{#ffbc32}{点赞} 评 论 \color{#2d85f0}{评论} 收 藏 \color{#0aa858}{收藏} 关 注 \color{#f4433c}{关注}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值