vue13--程式設計式路由的實現
阿新 • • 發佈:2021-02-14
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>程式設計式路由的實現</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <div> <button type="button" @click="fun1()">跳轉1</button> </div> <div> <button type="button" @click="fun2()">跳轉2</button> </div> <div> <button type="button" @click="fun3()">跳轉3</button> </div> <router-view></router-view> </div> <script> //定義路由項 const router = new VueRouter({//路由物件,例項的定義 routes:[//定義路由項 { path:'index/:id', name:'index', component:{ template:'<div>{{$route.params.id}}</div>'//接路由方式的 跳轉 } }, { path:'/test/:id', name:'test', component:{ template:'<div>{{$route.params.id}}</div>'//接路由方式的 跳轉 } }, { path:'/go', name:'go', component:{ template:'<div>{{$route.query.uid}}</div>'//接路由方式的 跳轉 } } ] }); let vm = new Vue({ el:'#app', router,//註冊到vue例項中 methods:{ fun1(){ //replace方法實現路由跳轉,根據路由項的name進行跳轉 this.$router.replace({name:'index',params:{id:Math.random()}}); }, fun2(){ //push方法實現路由跳轉,根據路由項的path進行跳轉 this.$router.push(`/test/${Math.random()}`); }, fun3(){ this.$router.push({path:'/go',query:{uid:110}}); } } }); </script> </body> </html>