Spec-Zone.ru › Vue Router 3

Начало работы

Примечание

В примерах кода в руководстве будет использоваться ES2015.

Кроме того, во всех примерах будет использоваться полная версия Vue для возможности компиляции шаблонов в режиме реального времени. Более подробную информацию см. здесь.

Просмотреть бесплатный видеокурс по Vue Router на Vue School

Создание одностраничного приложения с Vue + Vue Router интуитивно понятно: с Vue.js мы уже составляем наше приложение из компонентов. При добавлении Vue Router в микс, все, что нам нужно сделать, это сопоставить наши компоненты с маршрутами и указать Vue Router, где их отображать. Вот базовый пример:

HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- use router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will be rendered as an `<a>` tag by default -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</div>

JavaScript

// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.

// 1. Define route components.
// These can be imported from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
  routes // short for `routes: routes`
})

// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
  router
}).$mount('#app')

// Now the app has started!

Инжектируя маршрутизатор, мы получаем к нему доступ как this.$router а также к текущему маршруту как this.$route внутри любого компонента:

// Home.vue
export default {
  computed: {
    username() {
      // We will see what `params` is shortly
      return this.$route.params.username
    }
  },
  methods: {
    goBack() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
    }
  }
}

В документации мы часто будем использовать router экземпляр. Имейте в виду, что this.$router полностью эквивалентно использованию router. Причина, по которой мы используем this.$router заключается в том, чтобы не импортировать маршрутизатор в каждый отдельный компонент, которому необходимо манипулировать маршрутизацией.

Вы также можете посмотреть этот пример вживую.

Обратите внимание, что <router-link> автоматически получает класс .router-link-active при совпадении с целевым маршрутом. Более подробную информацию см. в его справочнике по API.

← Установка Динамическое сопоставление маршрутов →

© 2013–present Evan You
Licensed under the MIT License.
https://router.vuejs.org/guide/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API