前置知识请戳这里
vue-routerCDN地址:https://unpkg.com/[email protected]/dist/vue-router.js
vue-router下载地址:https://github.com/vuejs/vue-router/tree/dev/dist
vue2.0路由基本写法
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script> </head> <body> <div id="app"> <router-link to="/login">登录</router-link> <router-link to="/register">注册</router-link> <!--组件的显示占位域--> <router-view></router-view> </div> <script> //1.0 准备组件 var App = Vue.extend({}); var login = Vue.extend({ template: ‘<div><h3>登录</h3></div>‘ }); var register = Vue.extend({ template: ‘<div><h3>注册</h3></div>‘ }) //2.0 实例化路由规则对象 var router = new VueRouter({ routes: [{ path: ‘/login‘, component: login }, { path: ‘/register‘, component: register }, { path:‘/‘, //当路径为/时,重定向到/login redirect:‘/login‘ } ] }); //3.0 开启路由对象 new Vue({ el: ‘#app‘, router: router }) </script> </body> </html>
vue2.0路由传参
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script> </head> <body> <div id="app"> <router-link to="/login">登录</router-link> <router-link to="/register/value">注册</router-link> <!--组件的显示占位域--> <router-view></router-view> </div> <script> //1.0 准备组件 var App = Vue.extend({}); var login = Vue.extend({ template: ‘<div><h3>登录</h3></div>‘ }); var register = Vue.extend({ template: ‘<div><h3>注册{{name}}</h3></div>‘, data:function(){ return { name:‘‘ } }, created:function(){ this.name = this.$route.params.name; } }); //2.0 实例化路由规则对象 var router = new VueRouter({ routes: [{ path: ‘/login‘, component: login }, { path: ‘/register/:name‘, component: register }, { path:‘/‘, //当路径为/时,重定向到/login redirect:‘/login‘ } ] }); //3.0 开启路由对象 new Vue({ el: ‘#app‘, router: router }) </script> </body> </html>