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>