欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue 动态路由,路由嵌套

程序员文章站 2022-06-02 20:14:49
...

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}{关注}