1、文件結構css
2、vue.jshtml
打開此連接 https://cdn.bootcss.com/vue/2.6.10/vue.js vue
複製粘貼頁面的全部內容vue-router
3、vue-router.js數組
打開此連接 https://cdn.bootcss.com/vue-router/3.0.6/vue-router.js瀏覽器
複製粘貼頁面的全部內容app
4、index.html函數
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>title</title> 8 </head> 9 <body> 10 <div id="app"> 11 <h1>元數據及路由匹配</h1> 12 13 <router-link to="/">首頁</router-link> 14 <router-link to="/login">登陸</router-link> 15 <router-link to="/post">帖子管理</router-link> 16 <router-link to="/a">A</router-link> 17 18 19 <router-view></router-view> 20 </div> 21 22 23 <script src="../lib/vue.js"></script> 24 <script src="../lib/vue-router.js"></script> 25 <script src="js/app.js"></script> 26 </body> 27 </html>
5、app.jspost
1 var routes = [ 2 { 3 path:"/", 4 component:{ 5 template:` 6 <h1>首頁</h1> 7 ` 8 } 9 }, 10 { 11 path:"/a", 12 // 設置元數據屬性,下面表示須要登陸後才能夠路由到/post 13 meta:{ 14 login_required:true 15 }, 16 component:{ 17 template:` 18 <h1>A</h1> 19 ` 20 } 21 }, 22 { 23 path:"/login", 24 component:{ 25 template:` 26 <h1>登陸</h1> 27 ` 28 } 29 }, 30 { 31 path:"/post", 32 // 設置元數據屬性,下面表示須要登陸後才能夠路由到/post 33 meta:{ 34 login_required:true 35 }, 36 component:{ 37 template:` 38 <div> 39 <h1>帖子管理</h1> 40 41 <router-link to="look" append>查看帖子</router-link> 42 <router-view></router-view> 43 </div> 44 ` 45 }, 46 children:[ 47 { 48 path:"look", 49 component:{ 50 template:` 51 <h2>這是今天寫的一個帖子</h2> 52 ` 53 } 54 } 55 ] 56 }, 57 ]; 58 59 var router = new VueRouter({ 60 routes 61 }); 62 63 router.beforeEach(function(to,from,next){ 64 65 // VueRouter對象的beforeEach(function(to,from,next){})方法和afterEach(function(to,from){}), 66 // 稱爲導航鉤子,能夠控制訪問權限和驗證 67 // 裏面的回調函數能夠在路由前和路由後進行操做處理 68 69 logged_in = false; 70 // 方法一:導航鉤子,來進行路由前的驗證 71 // if(!logged_in && to.path == "/post"){ 72 // next("/login"); 73 // }else{ 74 // next(); 75 // } 76 77 78 // vue提供了一個matched屬性,獲得的是一個數組,好比子路由/post/look,就匹配/post/look和/post 79 // console.log("to.matched:",to.matched); 80 81 // js數組有一個some方法,方法裏能夠用回調函數,來遍歷處理數組的每項 82 // to.matched.some(function(item){ 83 84 // }) 85 86 // 方法一驗證了/post,若是含有子路由,好比/post/look,則無法驗證,因此必須保證父路由及其後面全部的子路由 87 // 都能接受驗證 88 // 解決方法:迭代數組裏的每一項,只要有一項的path是/post,就跳向登陸界面 89 // 方法二 90 // if(!logged_in && to.matched.some(function(item){ 91 // return item.path == "/post" 92 // })){ 93 // next('/login'); 94 // }else{ 95 // next() 96 // } 97 98 99 // 第二種方法:寫死了,對於一個頁面(好比/post及其子路由)的驗證是能夠的, 100 // 但若是有多個路由(好比還有/a),就又得再寫驗證 101 102 // 方法三:在組件內設置元數據,更靈活 103 if(!logged_in && to.matched.some(function(item){ 104 return item.meta.login_required 105 })){ 106 next("/login"); 107 }else{ 108 next(); 109 } 110 }); 111 112 new Vue({ 113 el:"#app", 114 router 115 })
6、瀏覽器效果ui
7、謝謝觀看,若有問題,隨時交流哦