一、引入vue-router.js庫javascript
二、建立路由所需的模塊(組件):html
//合寫 <script> var vm=new Vue({ el:'#box', data:{}, //添加路由的配置項 //router:路由對象(實例) //router:new VueRouter() //設置路由對象的配置項 /*new VueRouter({ 路徑信息:路徑信息盛放在數組中 routes:[ {path:'分配的url路徑',component:'組件名'} ] }) */ router:new VueRouter({ routes:[ {path:'/home',component:{ template:'<h2>首頁</h2>' }}, {path:'/news',component:{ template:'<h2>新聞</h2>' }}, {path:'/hot',component:{ template:'<h2>熱點</h2>' }}, ] }) }) </script>
//分寫,相對經常使用 <script> //一、準備路由所需的模塊(組件) //全局Vue下,有extend(),用來註冊路由所需的模塊(組件) var Home=Vue.extend({ template:'#home' }); var News=Vue.extend({ template:'#news' }); var Hot=Vue.extend({ template:'#hot' }); var arr=[ {path:'/home',component:Home}, {path:'/news',component:News}, {path:'/hot',component:Hot} ]; var router=new VueRouter({ routes: arr }); var vm=new Vue({ el:'#box', data:{}, router:router }) //路由重定向 //push():路由對象自帶方法,進行路由跳轉push('url') router.push('/home') </script>
三、更改HTML結構vue
<div id="box"> <ul> <li><router-link to='/home'>home</router-link></li> <li><router-link to='/news'>news</router-link></li> <li><router-link to='/hot'>hot</router-link></li> </ul> <div class="show"> <router-view></router-view> </div> </div>
效果以下(分別是點擊了home和news以後的效果)java
四、路由的重定向,做用是在刷新以後從新定向到一個模塊(組件/URL)上去vue-router
//即爲上面路由配置的合寫代碼中最下面的寫法 //路由重定向push():路由對象自帶方法,進行路由跳轉push('url') router.push('/home')
beforeCrate:function(){ this.$router.push('/home') }