关于vue-router的基本使用方法
首先,需要下载vue-router
npm install vue-router --save
vue-router在html或组件中的展现
```
<div id="box">
<ul>
<li><router-link to="/home">Home</router-link></li>
<li><router-link to="/news">News<router-link></li>
</ul>
<router-view></router-view>
</div>
<script src="vue.js"></script>
<script src="vue-router.js"></script>
<script>
//路由配置
//组件
var Home={template: '<div><h3>我是主页</h3></div>'}
var News={template: '<div><h3>我是新闻页</h3></div>'}
var routes=[
{path: '/home',component: Home},
{path: '/news',component: News}
]
var router=new VueRouter({
routes: routes
});
new Vue({
el: '#box',
router: router
});
</script>
```
嵌套路由
```
<div id="box">
<ul>
<li><router-link to="/home">Home</router-link></li>
<li><router-link to="/news">News<router-link></li>
</ul>
<router-view></router-view>
</div>
<script src="vue.js"></script>
<script src="vue-router.js"></script>
<script>
//路由配置
//组件
var Home={
template: '<div><h3>我是主页</h3>'+
'<ul>'+
'<li><router-link to="/home/login">Login</router-link></li>'+
'<li><router-link to="/home/reg">Register<router-link></li>'+
'</ul>'+
'<router-view></router-view>'+
'</div>'
}
var Login={template: '<div><h3>我是登录</h3></div>'}
var Reg={template: '<div><h3>我是注册</h3></div>'}
var News={
template: '<div><h3>我是新闻页</h3>'+
26 '<ul>'+
'<li><router-link to="/home/detail/001">第一条新闻</router-link></li>'+
'<li><router-link to="/home/detail/002">第二条新闻<router-link></li>'+
'</ul>'+
'<router-view></router-view>'+
'</div>'
}
var Detail={template: '<div>{{$route.params}}</div>'}
/*$route.params可获取当前的{"id":"001"}
*$route.query可获取到url后的参数?a=22&b=kk,{"a":"22","b":"kk"}
*/
var routes=[
{path: '/',component: Home},//默认访问主页
{
path: '/home',
component: Home,
children: [
{path: '/home/login',component: Login},
{path: '/home/reg',component: Reg}]
},
{
path: '/news',
48 component: News,
children: [
{path: '/news/detail/:id',component:Detail}//这点要注意
]
}
]
var router=new VueRouter({
routes: routes
});
new Vue({
el: '#box',
router: router
});
</script>
```
原文地址:https://github.com/TimWST/blog/blob/master/js/vue-router.md