我們常說的路由是應(yīng)用于SPA應(yīng)用,所謂的單頁面應(yīng)用,這是h5新出的一種頁面應(yīng)用模式,就是通過不同的路徑(url),達(dá)到不同的效果,來使組件之間變化和切換。vue路由,當(dāng)然需要引用文件vue-router.js,可以通過npm,bower進(jìn)行下載,官方文檔 http://router.vuejs.org/zh-cn/index.html
<div id="box">
<div>
<router-link to="/home">主頁</router-link>
<router-link to="/news">新聞</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
<script>
//組件
var Home={
template:'<h3>我是主頁</h3>'
};
var News={
template:'<h3>我是新聞</h3>'
};
//配置路由
const routes=[
{path:'/home', component:Home},
{path:'/news', component:News},
{path:'*', redirect:'/home'}
];
//生成路由實例
const router=new VueRouter({
routes
});
//最后掛到vue上
new Vue({
router,
el:'#box'
});
</script>
</body>
路由間的嵌套:
<div id="box">
<div>
<router-link to="/home">主頁</router-link>
<router-link to="/user">用戶</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
<script type="text/javascript">
//組件
var Home={
template:"<h3>我是主頁</h3>"
}
var User={
template:`
<div>
<h3>我是用戶信息</h3>
<ul>
<li><router-link to="/user/username">某個用戶</router-link></li>
</ul>
<div>
<router-view></router-view>
</div>
</div>
`
}
var Username={
template:'<h3>我是xx用戶</h3>'
}
//配置路由
const routes=[
{path:'/home',component:Home},
{path:'/user',component:User,
children:[
{path:'/user/username',component:Username}
]
},
{path:'*',redirect:'home'}
];
const router=new VueRouter({
routes
})
var vm=new Vue({
router,
el:'#box'
})
</script>
</body>```
路由里面有兩個注意的方法:
router.push({path:'home'}); //直接添加一個路由,表現(xiàn)切換路由,本質(zhì)往歷史記錄里面添加一個。
router.replace({path:'news'}) //替換路由,不會往歷史記錄里面添加。