本案例代码将使用 ES2015 来编写。

Vue.js + Vue Router 创建单页应用,是非常简单的。使用Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来。我们需要做的是,将组件 (components)映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。 下面是个基本例子:

HTML

  1. <script src="https://unpkg.com/vue/dist/vue.js"> </script>
  2. <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  3. <div id="app">
  4. <h1> hello app!</h1>
  5. <!-- 使用router-link 组件来导航 -->
  6. <!-- 通过传入 'to' 属性指定链接 -->
  7. <!-- <router-link> 默认会被渲染成一个 <a> 标签 -->
  8. <p>
  9. <router-link to="/foo"> Go to Foo </router-link>
  10. <router-link to="/bar"> Go to Bar </router-link>
  11. </p>
  12. <!-- 路由出口 -->
  13. <!-- 路由匹配到的组件将渲染在这里-->
  14. <router-view></router-view>

JavaScript

  1. // 0. 如果使用模块化机制变成,导入Vue和VurRouter,要调用 Vue.use(VueRouter)
  2. // 1. 定义 (路由) 组件
  3. // 可以从其他文件 import 进来
  4. const Foo = {template:'<div> Foo </div>'}
  5. cosnt Bar = {template:'<div> Bar </div>'}
  6. // 2. 定义路由
  7. // 每个路由应该映射一个组件。。其中component 可以是
  8. // 通过Vue.extend() 创建的组件构造器
  9. // 或者,只是一个组件配置对象。
  10. // 我们晚点再讨论嵌套路由
  11. const routes = [
  12. {path:'/',component:FOO}, // 默认
  13. {path:'/foo',component:Foo},
  14. {path:'/bar',component:Bar}
  15. ]
  16. // 3. 创建 router 实例,然后传 routes 配置
  17. // 还有传别的配置参数,不过先这么简单着吧。
  18. const router = new VueRouter({
  19. routes:routes // 也可缩写 routes
  20. })
  21. // 4. 创建和挂载根实例。
  22. // 记得要通过 router 配置参数注入路由
  23. // 从而让真个应用都有路由功能
  24. const app = new Vue({
  25. router
  26. }).$mount('#app')

通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由:

  1. // Home.vue
  2. export default{
  3. computed:{
  4. username(){
  5. // 我们很块就会看到 ‘params’ 是什么
  6. return this.$route.params.username
  7. }
  8. },
  9. methods:{
  10. goBack(){
  11. window.history.length >1?this.$router.go(-1):this.$router.push('/')
  12. }
  13. }
  14. }

该文档通篇使用 router 实例。
留意以下 this.$router router 使用起来完全一样。
我们使用 this.$router 的原因是我们并不想在每个独立需要封装路由的组件中都导入路由。

要注意, 当 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active/