vue.js一級、二級、重定向路由配置
阿新 • • 發佈:2018-11-05
方法一
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>Document</title> <script src="vue.js" type="text/javascript" charset="utf-8"></script> <script src="vue-router.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> li{ list-style: none; display: inline-block; margin: 20px 10px; } a{ text-decoration: none; } .show{ height: 200px; width: 500px; background-color: gold; } </style> </head> <body> <div id="div"> <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> <template id="home"> <h1>首頁</h1> </template> <template id="news"> <h1>新聞</h1> </template> <template id="hot"> <div> <h1>熱點</h1> <router-link to='/hot/mv'>MV</router-link> <router-link to='/hot/tv'>TV</router-link> <router-view></router-view> </div> </template> </body> </html> <script type="text/javascript"> // 生成並繫結路由模組 var Home = Vue.extend({ template: '#home' }); var News = Vue.extend({ template: '#news' }); var Hot = Vue.extend({ template: '#hot' }); // 配置路徑資訊 var routes = [ // 一級路由 {path: '/home',component:Home}, {path: '/news',component:News}, // 二級路由 {path: '/hot',component:Hot,children:[ {path:'',component:{template:'<p>電影:戰狼,戰狼2,戰狼3'}},//預設模板 {path:'mv',component:{template:'<p>電影:戰狼,戰狼2,戰狼3'}}, {path:'tv',component:{template:'<p>電視劇:大秦帝國,大秦帝國2,大秦帝國3'}}, ]}, ]; // 建立路由物件 var router = new VueRouter({ routes:routes }); // 新增路由配置項 var vm = new Vue({ el: '#div', data:{ }, // 重新整理頁面跳轉 beforeCreate:function(){ this.$router.push('/home'); }, router:router }) // 重新整理頁面跳轉 // router.push('/news'); </script>
方法二
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>Document</title> <script src="vue.js" type="text/javascript" charset="utf-8"></script> <script src="vue-router.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> li{ list-style: none; display: inline-block; margin: 20px 10px; } a{ text-decoration: none; } .show{ height: 200px; width: 300px; background-color: #ccc; } </style> </head> <body> <div id="div"> <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> </body> </html> <script type="text/javascript"> var vm = new Vue({ el: '#div', data:{ }, router:new VueRouter({ routes:[ {path:'/home',component:{template:'<h1>首頁</h1>'}}, {path:'/news',component:{template:'<h1>新聞</h1>'}}, {path:'/hot',component:{template:'<h1>熱點</h1>'}} ] }) }) </script>