一.vue路由
https://router.vuejs.org/zh-cn/
1.bower下载vue-router
vue的里的链接
<router-link to="/home"></router-link>
1.引入vue与vue-router
<script src="bower_components/vue/dist/vue.js"></script> <script src="bower_components/vue-router/dist/vue-router.js"></script>
HTML
<div id="app"> <div> <router-link to="/home">主页</router-link> <router-link to="/news">新闻</router-link> </div> <div> <router-view></router-view> </div> </div>
vue.js
var Home = { template: "<h3>我是主页</h3>" } var News = { template: "<h3>我是新闻</h3>" } // 配置路由 var routes = [ {path: "/home", component:Home}, {path: "/news", component:News}, {path: "*", redirect:"/home"} // 重定向 ] // 生成路由实例 var router = new VueRouter({ routes }) // 最后挂到vue上 new Vue({ el: "#app", router: router })
二.vue路由嵌套
var Home = { template: "<h3>我是主页</h3>" } var UserDetail = { template: "<h3>我是XX用户</h3>" } var Uesr = { template: ` <div class="user"> <h3>我是用户</h3> <ul> <li><router-link to="/user/username">某个用户</router-link></li> </ul> <div> <router-view></router-view> </div> </div> ` } // 配置路由 var routes = [ {path: "/home", component:Home}, { path: "/user", component:Uesr, children: [ {path:"username", component:UserDetail} ] }, {path: "*", redirect:"/home"} // 重定向 ] // 生成路由实例 var router = new VueRouter({ routes }) // 最后挂到vue上 new Vue({ el: "#app", router: router })
三.有参数的路由, $route.params
var Home = { template: "<h3>我是主页</h3>" } var UserDetail = { template: "<h3>{{$route.params}}</h3>" } var Uesr = { template: ` <div class="user"> <h3>我是用户</h3> <ul> <li><router-link to="/user/strive/age/10">strive</router-link></li> <li><router-link to="/user/blue/age/80">blue</router-link></li> <li><router-link to="/user/eric/age/70">eric</router-link></li> </ul> <div> <router-view></router-view> </div> </div> ` } // 配置路由 var routes = [ {path: "/home", component:Home}, { path: "/user", component:Uesr, children: [ {path:":username/age/:age", component:UserDetail} ] }, {path: "*", redirect:"/home"} // 重定向 ] // 生成路由实例 var router = new VueRouter({ routes }) // 最后挂到vue上 new Vue({ el: "#app", router: router })
四.路由实例方法
1.router.push({path:"home"}); // 直接添加路由, 往历史记录里添加一个 2.router.replace({path:"home"}) // 替换路由, 不在历史记录