通過VueRouter來實現組件之間的跳轉,供大家參考,具體內容如下
提供了3種方式實現跳轉:
①直接修改地址欄中的路由地址
<!doctype html><html> <head> <meta charset="UTF-8"> <title></title> <script src="js/vue.js"></script><!-- 引入文件 --> <script src="js/vue-router.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p><!--通過router-view指定盛放組件的容器 --> <router-view></router-view> </div> <script> var testLogin = Vue.component("login",{ template:` <div> <h1>這是我的登錄頁面</h1> </div> ` }) var testRegister = Vue.component("register",{ template:` <div> <h1>這是我的注冊頁面</h1> </div> ` }) //配置路由詞典 //對象數組 const myRoutes =[ //當路由地址:地址欄中的那個路徑是myLogin訪問組件 //組件是作為標簽來用的所以不能直接在component后面使用 //要用返回值 //path:''指定地址欄為空:默認為Login頁面 {path:'',component:testLogin}, {path:'/myLogin',component:testLogin}, {path:'/myRegister',component:testRegister} ] const myRouter = new VueRouter({ //myRoutes可以直接用上面的數組替換 routes:myRoutes }) new Vue({ router:myRouter, //或者: /* router:new VueRouter({ routes:[ {path:'/myLogin',component:testLogin}, {path:'/myRegister',component:testRegister} ] }) */ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body></html>②通過router-link實現跳轉
<router-link to="/myRegister">注冊</router-link>
<!doctype html><html> <head> <meta charset="UTF-8"> <title></title> <script src="js/vue.js"></script><!-- 引入文件 --> <script src="js/vue-router.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p><!--通過router-view指定盛放組件的容器 --> <router-view></router-view> </div> <script> var testLogin = Vue.component("login",{ template:` <div> <h1>這是我的登錄頁面</h1> <router-link to="/myRegister">注冊</router-link> </div> ` /*to后面是路由地址*/ }) var testRegister = Vue.component("register",{ template:` <div> <h1>這是我的注冊頁面</h1> </div> ` }) //配置路由詞典 const myRoutes =[ {path:'',component:testLogin}, {path:'/myLogin',component:testLogin}, {path:'/myRegister',component:testRegister} ] const myRouter = new VueRouter({ routes:myRoutes }) new Vue({ router:myRouter, el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body></html>
新聞熱點
疑難解答
圖片精選