用 Vue.js + vue-router 建立单页应用,是很是简单的。使用 Vue.js ,咱们已经能够经过组合组件来组成应用程序,当你要把 vue-router 添加进来,咱们须要作的是,将组件(components)映射到路由(routes),而后告诉 vue-router 在哪里渲染它们。html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> /* 实现当前 路由导航高亮 */ .router-link-exact-active, .router-link-active { color: red; font-size: 30px; } </style> </head> <body> <div id="app"> <!-- 路由的入口,也就是a标签 --> <router-link to="/home">home</router-link> <router-link to="/about">about</router-link> <!-- 指定页面中路由的出口,也就是:路由匹配组件未来展现在页面中的位置 --> <router-view></router-view> </div> <script src="./vue.js"></script> <!-- 引入 路由插件 --> <script src="./node_modules/vue-router/dist/vue-router.js"></script> <script> /* 路由的使用步骤: 1 引入 路由插件的js文件 2 建立几个组件 3 经过 VueRouter 来建立一个路由的实例,而且在参数中配置好路由规则 4 将 路由实例 与 Vue实例关联起来,经过 router 属性 5 在页面中使用 router-link 来定义导航(a标签) 路由路口 6 在页面中使用 router-view 来定义路由出口(路由内容展现在页面中的位置) */ // Vue中的路由是:哈希值 和 组件的对应关系 // component 方法可以返回一个对象,用这个对象就能够表示当前组件 const Home = Vue.component('home', { template: `<h1>这是 Home 组件</h1>` }) const About = Vue.component('about', { template: `<h1>这是 About 组件</h1>` }) // 配置路由规则 const router = new VueRouter({ // 经过 routes 来配置路由规则,值:数组 routes: [ // 数组中的每一项表示一个具体的路由规则 // path 用来设置浏览器URL中的哈希值 // componet 属性用来设置哈希值对应的组件 { path: '/home', component: Home }, { path: '/about', component: About }, // redirect 重定向: 让当前匹配的 / ,跳转到 /home 对应的组件中, 也就是默认展现: home组件 { path: '/', redirect: '/home' } ] }) var vm = new Vue({ el: '#app', // Vue的配置对象中有一个配置项叫作:router // 用来指定当前要使用的路由 // router: router router }) </script> </body> </html>
/
重定向到 /home
{ path: '/', redirect: '/home' }
router-link-exact-active router-link-active
类/user/:id
$route.query
获取到 URL 中的查询参数 等// 连接: <router-link to="/user/1001">用户 Jack</router-link> <router-link to="/user/1002">用户 Rose</router-link> // 路由: { path: '/user/:id', component: User } // User组件: const User = { template: `<div>User {{ $route.params.id }}</div>` }
router-view
,在路由规则中使用 children
配置// 父组件: const User = Vue.component('user', { template: ` <div class="user"> <h2>User Center</h2> <router-link to="/user/profile">我的资料</router-link> <router-link to="/user/posts">岗位</router-link> <!-- 子路由展现在此处 --> <router-view></router-view> </div> ` }) // 子组件: const UserProfile = { template: '<h3>我的资料:张三</h3>' } const UserPosts = { template: '<h3>岗位:FE</h3>' } { path: '/user', component: User, // 子路由配置: children: [ { // 当 /user/profile 匹配成功, // UserProfile 会被渲染在 User 的 <router-view> 中 path: 'profile', component: UserProfile }, { // 当 /user/posts 匹配成功 // UserPosts 会被渲染在 User 的 <router-view> 中 path: 'posts', component: UserPosts } ] }
vm.$router.go(-1);
$route.path 当前路由对象的路径,如'/vi $route.query 请求参数,如/foo?user=1获取到query.user = 1 $route.router 所属路由器以及所属组件信息 $route.matched 数组,包含当前匹配的路径中所包含的全部片断所对应的配置参数对象。 $route.name 当前路径名字