使用 Vue Router 介绍 Vue.js 中的路由功能

路由是任何非平凡的SPA的重要组成部分,应该是任何框架的核心组成部分。对于Vue,这种功能是由官方Vue Router插件提供的。

安装 & 设置

首先,当然,我们需要安装并启用Vue Router插件,使用Yarn或NPM安装Vue-router。

1# Yarn
2$ yarn add vue-router
3# NPM
4$ npm install vue-router --save

然后,我们需要启用插件:

 1[label main.js]
 2import Vue from 'vue';
 3import VueRouter from 'vue-router';
 4import App from './App.vue';
 5// These are the routes we're going to create.
 6import ourRoutes from './our-routes.js';
 7
 8Vue.use(VueRouter);
 9
10// We create the router instance here.
11const router = new VueRouter({
12  routes: ourRoutes
13});
14
15// The usual app stuff goes here.
16const app = new Vue({
17  //
18  router,
19  render: h => h(App)
20}).$mount('#app');

我们需要一个地方来渲染我们的路线. 为此,我们使用 组件。

1[label App.vue]
2<template>
3  <div id="app">
4    <h1>Random App Title</h1>
5    <!-- Routes get rendered here -->
6    <router-view></router-view>
7  </div>
8</template>

定义路线

好吧,让我们现在创建一些路线,正如你所看到的,我们已经导入了目前尚不存在的 our-routes.js 文件,让我们现在创建它。

路线定义只是包含路线对象的数组,为本指南的目的,我们将假设您有三个目标路线:RouteOne.vue、RouteTwo.vue 和 RouteOneChild.vue。

 1[label our-routes.js]
 2import RouteOne from './RouteOne.vue';
 3import RouteOneChild from './RouteOneChild.vue';
 4import RouteTwo from './RouteTwo.vue';
 5
 6export default [
 7  // Redirects to /route-one as the default route.
 8  {
 9    path: '/',
10    redirect: '/route-one'
11  },
12  {
13    path: '/route-one',
14    component: RouteOne,
15    // Children is just another route definition of sub-routes.
16    children: [
17      {
18        // Note: No leading slash. This can trip people up sometimes.
19        path: 'route-one-child',
20        component: RouteOneChild
21      }
22    ]
23  },
24  {
25    // Route two takes the route parameter "id".
26    // The parameter value can be accessed with $route.params.id in the RouteTwo component.
27    path: '/route-two/:id',
28    component: RouteTwo
29  }
30];

连接到路线

您可能想要链接到应用程序中的路线,而不是使用正常的 标签,而是使用

文档

路由还有很多,我们刚刚开始了! 有关更多信息,请参阅 官方文档

Published At
Categories with 技术
Tagged with
comments powered by Disqus