Vue 项目实战之 Vue Router

743 阅读1分钟

最近在写的 Vue 版记账项目应用了 Vue Router。它是通过管理 URL,实现组件的切换和状态的变化。在项目中用到的一些功能在此做一个学习记录。

安装

npm install vue-router

基础用法

  • 在模块化的项目中使用 通过 Vue.use(VueRouter) 明确地安装路由功能:
  • 将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。 举个栗子:制作一个导航栏:有2个页面由路由器处理:一个主页,一个用户页面。 当单击不同的 Link,路由器呈现匹配对应的页面。
//  index.ts:

import Vue from "vue";
import VueRouter from "vue-router";
import Detail from "@/views/Detail.vue";
import Account from "@/views/Account.vue";
import NotFound from "@/views/NotFound.vue";

Vue.use(VueRouter);

const routes = [
// 默认进入 Account 组件 
  {
    path: "/",
    component: Account
  },
  {
    path: "/account",
    component: Account
  },
  //  当url 与以上路由不匹配将渲染 NotFound 组件
  {
    path: "*",
    component: NotFound
  },
];

const router = new VueRouter({
  routes
});

export default router;
//  App.vue

<template>
  <div id="app" >
    <router-view/>
  </div>
</template>

重定向

  • 通过 routes 配置来完成,从 / 重定向到 /account:
{
    path: "/",
    redirect: "/account",
  },

router-link

  • 使用 router-link 组件来导航
  • 通过传入 to 属性指定链接
  • router-link 标签 默认会被渲染成一个 a 标签
  • 当 router-link 对应的路由匹配成功,出现 selected 的类表示路由激活
this.$route.params.id
<router-link to="/detail" active-class="selected">记账</router-link>

this.$routerthis.$route

  • 通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由:
  • this.$router.back() 返回上一个页面
  • this.$router.push('/') 定位到默认路由对应的页面
  • this.$route.params.id 获取参数

路由组件传参

  • 添加路由
{
    path: "/record/:id",
    component: Record
  }
  • 导航指定组件
  <router-link :to="`/record/${xx}`">跳转到 Record 组件</router-link>