2. vue-router简单使用

75 阅读2分钟

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

1. vue-router简单使用

1.gif

image.png

<!DOCTYPE html>
<html>
  <head>
    <title>vue-router</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router@3.1.3/dist/vue-router.js"></script>
  </head>
  <body>
    <div id="app">
      <h1>Hello App!</h1>
      <p>
        <!-- 使用 router-link 组件来导航. -->
        <!-- 通过传入 `to` 属性指定链接. -->
        <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
        <router-link to="/foo">Go to Foo</router-link>
        <router-link to="/bar">Go to Bar</router-link>
      </p>
      <!-- 路由出口 -->
      <!-- 路由匹配到的组件将渲染在这里 -->
      <router-view></router-view>
    </div>
    <script>
      // 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
      // 1. 定义 (路由) 组件。
      // 可以从其他文件 import 进来
      const Foo = { template: "<div>foo</div>" };
      const Bar = { template: "<div>bar</div>" };

      // 2. 定义路由
      // 每个路由应该映射一个组件。 其中"component" 可以是
      // 通过 Vue.extend() 创建的组件构造器,
      // 或者,只是一个组件配置对象。
      // 我们晚点再讨论嵌套路由。
      const routes = [
        { path: "/foo", component: Foo },
        { path: "/bar", component: Bar }
      ];

      // 3. 创建 router 实例,然后传 `routes` 配置
      // 你还可以传别的配置参数, 不过先这么简单着吧。
      const router = new VueRouter({
        routes // (缩写) 相当于 routes: routes
      });

      // 4. 创建和挂载根实例。
      // 记得要通过 router 配置参数注入路由,
      // 从而让整个应用都有路由功能
      const app = new Vue({
        router,
        created() {
          console.log(this.$router instanceof VueRouter);
          console.log(this.$route instanceof VueRouter);
        }
      }).$mount("#app");

      // 现在,应用已经启动了!
    </script>
  </body>
</html>
  • 通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由:

image.png

// Home.vue
export default {
  computed: {
    username() {
      // 我们很快就会看到 `params` 是什么
      return this.$route.params.username
    }
  },
  methods: {
    goBack() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
    }
  }
}

2. this.$route 访问当前路由

image.png

3. this.$router 访问路由器

我们使用 this.$router 的原因是我们并不想在每个独立需要封装路由的组件中都导入路由。

image.png

4. <router-link> 组件

<router-link> 组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 <a> 标签,可以通过配置 tag 属性生成别的标签.。另外,当目标路由成功激活时,链接元素自动设置一个表示激活的 CSS 类名。

要注意,当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active。更多内容查看 API 文档 。

image.png