<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="contain" id="contain"> <h1>{{name}}</h1> <router-link to="/parent1">parent1</router-link> <router-link to="/parent2">parent2</router-link> <router-view></router-view> </div> <script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script> <script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.js"></script> <script type="text/javascript"> //建立組件 const parent1 = { template:'<h1>第一個父組件</h1>' }; const parent2 = { template:'<h1>第二個父組件</h1>' }; //定義路由映射 let routes= [{ path:'/',component:parent1, },{ path:'/parent1',component:parent1, },{ path:'/parent2',component:parent2, }]; //註冊路由 let router = new VueRouter({routes}); new Vue({ el:'#contain', data:{ name:'hwx' }, router:router//使用路由 }); </script> </body> </html>
使用name傳值javascript
使用params傳值css
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="contain" id="contain" > <h1>{{$route.name}}</h1> <router-link to="/parent1">parent1</router-link> <router-link to="/parent1/child1">child1</router-link> <router-link :to="{name:'parent1-child2',params:{id:123}}">child2</router-link> <router-link to="/parent2/1">parent2</router-link> <button @keyup.esc="goto('parent2',2)" @click="goto('parent2',2)">parent2</button> <router-view></router-view> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script> <script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.js"></script> <script type="text/javascript"> const parent1 = { template:'<div><h1>第一個父組件</h1> <router-view></router-view></div>', }; const child1 = { template:'<div><h1>第一個父組件的第一個child</h1></div>', }; const child2 = { template:'<div><h1>第一個父組件的第二個child,參數爲:{{$route.params.id}}</h1></div>', }; const parent2 = { template:'<h1>第二個父組件 參數爲:<span>{{$route.params.id}}</span></h1>' }; let routes= [{ path:'/', component:parent1, name:'parent1', children:[{ path:'',name:"default",component:child1 }] },{ path:'/parent1', component:parent1, name:'parent1', children:[ { path:'', name:'parent1-child1',component: child1}, { path:'child1',name:'parent1-child1', component: child1}, { path:'child2',name:'parent1-child2', component: child2} ] },{ path:'/parent2/:id', component:parent2, name:'parent2' }]; let router = new VueRouter({routes}); new Vue({ el:'#contain', data:{ name:'hwx', video:{ video_url:'Maggie.mp4' } }, router:router, mounted(){ }, methods:{ goto(name,id){ var url = "/"+name+"/"+id; this.$router.push({path:url}); } } }); </script> </body> </html>
再組件中設置路由羣html
<router-view></router-view> <router-view name="left" style="float: left; width: 50%; background: #eee;"></router-view> <router-view name="right" style="float: left; width: 50%; background: #f00;"></router-view>
配置路由vue
let routes= [{ path:'/', components:{ default:parent1, left:child1, right: child2 }, name:'parent1', }];
注:注意此處的components是複數形式,components的屬性值 == 路由羣中的name值java