├── .babelrc ├── .circleci └── config.yml ├── .eslintignore ├── .eslintrc ├── .flowconfig ├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md ├── funding.yml └── workflows │ └── release-tag.yml ├── .gitignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── assets └── browserstack-logo-600x315.png ├── build ├── build.js ├── configs.js └── rollup.dev.config.js ├── composables.d.ts ├── composables.js ├── composables.mjs ├── dist ├── vue-router.common.js ├── vue-router.esm.browser.js ├── vue-router.esm.browser.min.js ├── vue-router.esm.js ├── vue-router.js ├── vue-router.min.js └── vue-router.mjs ├── docs-gitbook ├── LANGS.md ├── assets │ ├── CNAME │ └── circle.yml ├── book.json ├── de │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ ├── api │ │ ├── component-injections.md │ │ ├── options.md │ │ ├── route-object.md │ │ ├── router-instance.md │ │ ├── router-link.md │ │ └── router-view.md │ ├── essentials │ │ ├── dynamic-matching.md │ │ ├── getting-started.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ └── redirect-and-alias.md │ └── installation.md ├── es │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ ├── api │ │ ├── component-injections.md │ │ ├── options.md │ │ ├── route-object.md │ │ ├── router-instance.md │ │ ├── router-link.md │ │ └── router-view.md │ ├── essentials │ │ ├── dynamic-matching.md │ │ ├── getting-started.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md │ └── installation.md ├── fr │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ ├── api │ │ ├── component-injections.md │ │ ├── options.md │ │ ├── route-object.md │ │ ├── router-instance.md │ │ ├── router-link.md │ │ └── router-view.md │ ├── essentials │ │ ├── dynamic-matching.md │ │ ├── getting-started.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md │ └── installation.md ├── gitbook │ └── images │ │ └── favicon.ico ├── ja │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ ├── api │ │ ├── component-injections.md │ │ ├── options.md │ │ ├── route-object.md │ │ ├── router-instance.md │ │ ├── router-link.md │ │ └── router-view.md │ ├── essentials │ │ ├── dynamic-matching.md │ │ ├── getting-started.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md │ └── installation.md ├── kr │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ ├── api │ │ ├── component-injections.md │ │ ├── options.md │ │ ├── route-object.md │ │ ├── router-instance.md │ │ ├── router-link.md │ │ └── router-view.md │ ├── essentials │ │ ├── dynamic-matching.md │ │ ├── getting-started.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md │ └── installation.md ├── old │ ├── README.md │ └── SUMMARY.md └── ru │ ├── README.md │ ├── SUMMARY.md │ ├── advanced │ ├── data-fetching.md │ ├── lazy-loading.md │ ├── meta.md │ ├── navigation-guards.md │ ├── scroll-behavior.md │ └── transitions.md │ ├── api │ ├── component-injections.md │ ├── options.md │ ├── route-object.md │ ├── router-instance.md │ ├── router-link.md │ └── router-view.md │ ├── essentials │ ├── dynamic-matching.md │ ├── getting-started.md │ ├── history-mode.md │ ├── named-routes.md │ ├── named-views.md │ ├── navigation.md │ ├── nested-routes.md │ ├── passing-props.md │ └── redirect-and-alias.md │ └── installation.md ├── docs ├── .vuepress │ ├── components │ │ ├── HomeSponsors.vue │ │ ├── HomeSponsorsGroup.vue │ │ └── sponsors.json │ ├── config.js │ ├── public │ │ ├── _redirects │ │ ├── bit-wide.png │ │ ├── icons │ │ │ ├── android-chrome-192x192.png │ │ │ ├── android-chrome-512x512.png │ │ │ ├── apple-touch-icon-120x120.png │ │ │ ├── apple-touch-icon-152x152.png │ │ │ ├── apple-touch-icon-180x180.png │ │ │ ├── apple-touch-icon-60x60.png │ │ │ ├── apple-touch-icon-76x76.png │ │ │ ├── apple-touch-icon.png │ │ │ ├── favicon-16x16.png │ │ │ ├── favicon-32x32.png │ │ │ ├── msapplication-icon-144x144.png │ │ │ ├── mstile-150x150.png │ │ │ └── safari-pinned-tab.svg │ │ ├── images │ │ │ └── vueschool │ │ │ │ ├── vs-close.svg │ │ │ │ ├── vs-fw-bg-small.svg │ │ │ │ ├── vs-fw-bg.svg │ │ │ │ ├── vs-iso.svg │ │ │ │ └── vs-logo.svg │ │ ├── logo.png │ │ └── sponsors │ │ │ ├── fincliplogo_black_svg.svg │ │ │ ├── fincliplogo_white_svg.svg │ │ │ ├── passionate-people-dark.png │ │ │ ├── passionate-people-light.png │ │ │ ├── vuejobs.png │ │ │ ├── vuetify-logo-dark-text.svg │ │ │ └── vuetify-logo-light-text.svg │ ├── styles │ │ └── index.styl │ └── theme │ │ ├── Layout.vue │ │ ├── components │ │ ├── BuySellAds.vue │ │ ├── CarbonAds.vue │ │ └── VueSchool │ │ │ └── BannerTop.vue │ │ └── index.js ├── README.md ├── api │ └── README.md ├── fr │ ├── README.md │ ├── api │ │ └── README.md │ ├── guide │ │ ├── README.md │ │ ├── advanced │ │ │ ├── data-fetching.md │ │ │ ├── lazy-loading.md │ │ │ ├── meta.md │ │ │ ├── navigation-guards.md │ │ │ ├── scroll-behavior.md │ │ │ └── transitions.md │ │ └── essentials │ │ │ ├── dynamic-matching.md │ │ │ ├── history-mode.md │ │ │ ├── named-routes.md │ │ │ ├── named-views.md │ │ │ ├── navigation.md │ │ │ ├── nested-routes.md │ │ │ ├── passing-props.md │ │ │ └── redirect-and-alias.md │ └── installation.md ├── guide │ ├── README.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-failures.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ └── essentials │ │ ├── dynamic-matching.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md ├── installation.md ├── ja │ ├── README.md │ ├── api │ │ └── README.md │ ├── guide │ │ ├── README.md │ │ ├── advanced │ │ │ ├── data-fetching.md │ │ │ ├── lazy-loading.md │ │ │ ├── meta.md │ │ │ ├── navigation-failures.md │ │ │ ├── navigation-guards.md │ │ │ ├── scroll-behavior.md │ │ │ └── transitions.md │ │ └── essentials │ │ │ ├── dynamic-matching.md │ │ │ ├── history-mode.md │ │ │ ├── named-routes.md │ │ │ ├── named-views.md │ │ │ ├── navigation.md │ │ │ ├── nested-routes.md │ │ │ ├── passing-props.md │ │ │ └── redirect-and-alias.md │ └── installation.md ├── kr │ ├── README.md │ ├── api │ │ └── README.md │ ├── guide │ │ ├── README.md │ │ ├── advanced │ │ │ ├── data-fetching.md │ │ │ ├── lazy-loading.md │ │ │ ├── meta.md │ │ │ ├── navigation-guards.md │ │ │ ├── scroll-behavior.md │ │ │ └── transitions.md │ │ └── essentials │ │ │ ├── dynamic-matching.md │ │ │ ├── getting-started.md │ │ │ ├── history-mode.md │ │ │ ├── named-routes.md │ │ │ ├── named-views.md │ │ │ ├── navigation.md │ │ │ ├── nested-routes.md │ │ │ ├── passing-props.md │ │ │ └── redirect-and-alias.md │ └── installation.md ├── ru │ ├── README.md │ ├── api │ │ └── README.md │ ├── guide │ │ ├── README.md │ │ ├── advanced │ │ │ ├── data-fetching.md │ │ │ ├── lazy-loading.md │ │ │ ├── meta.md │ │ │ ├── navigation-failures.md │ │ │ ├── navigation-guards.md │ │ │ ├── scroll-behavior.md │ │ │ └── transitions.md │ │ └── essentials │ │ │ ├── dynamic-matching.md │ │ │ ├── history-mode.md │ │ │ ├── named-routes.md │ │ │ ├── named-views.md │ │ │ ├── navigation.md │ │ │ ├── nested-routes.md │ │ │ ├── passing-props.md │ │ │ └── redirect-and-alias.md │ └── installation.md └── zh │ ├── README.md │ ├── api │ └── README.md │ ├── guide │ ├── README.md │ ├── advanced │ │ ├── data-fetching.md │ │ ├── lazy-loading.md │ │ ├── meta.md │ │ ├── navigation-failures.md │ │ ├── navigation-guards.md │ │ ├── scroll-behavior.md │ │ └── transitions.md │ └── essentials │ │ ├── dynamic-matching.md │ │ ├── history-mode.md │ │ ├── named-routes.md │ │ ├── named-views.md │ │ ├── navigation.md │ │ ├── nested-routes.md │ │ ├── passing-props.md │ │ └── redirect-and-alias.md │ └── installation.md ├── examples ├── active-links │ ├── app.js │ └── index.html ├── auth-flow │ ├── app.js │ ├── auth.js │ ├── components │ │ ├── About.vue │ │ ├── App.vue │ │ ├── Dashboard.vue │ │ └── Login.vue │ └── index.html ├── basic │ ├── app.js │ └── index.html ├── composables │ ├── app.js │ └── index.html ├── data-fetching │ ├── Post.vue │ ├── api.js │ ├── app.js │ └── index.html ├── discrete-components │ ├── app.js │ └── index.html ├── global.css ├── hash-mode │ ├── app.js │ └── index.html ├── hash-scroll-behavior │ ├── app.js │ └── index.html ├── index.html ├── keepalive-view │ ├── app.js │ └── index.html ├── lazy-loading-before-mount │ ├── app.js │ └── index.html ├── lazy-loading │ ├── Bar.vue │ ├── Baz.vue │ ├── Foo.vue │ ├── app.js │ └── index.html ├── multi-app │ ├── app.js │ └── index.html ├── named-routes │ ├── app.js │ └── index.html ├── named-views │ ├── app.js │ └── index.html ├── navigation-guards │ ├── app.js │ └── index.html ├── nested-router │ ├── app.js │ └── index.html ├── nested-routes │ ├── app.js │ └── index.html ├── redirect │ ├── app.js │ └── index.html ├── restart-app │ ├── app.js │ └── index.html ├── route-alias │ ├── app.js │ └── index.html ├── route-matching │ ├── app.js │ └── index.html ├── route-params │ ├── app.js │ └── index.html ├── route-props │ ├── Hello.vue │ ├── app.js │ └── index.html ├── router-errors │ ├── app.js │ └── index.html ├── scroll-behavior │ ├── app.js │ └── index.html ├── server.js ├── transitions │ ├── app.js │ └── index.html └── webpack.config.js ├── flow └── declarations.js ├── netlify.toml ├── package.json ├── scripts ├── release.sh └── verifyCommitMsg.js ├── src ├── components │ ├── link.js │ └── view.js ├── composables │ ├── globals.js │ ├── guards.js │ ├── index.js │ ├── useLink.js │ └── utils.js ├── create-matcher.js ├── create-route-map.js ├── entries │ ├── cjs.js │ └── esm.js ├── history │ ├── abstract.js │ ├── base.js │ ├── hash.js │ └── html5.js ├── index.js ├── install.js ├── router.js └── util │ ├── async.js │ ├── dom.js │ ├── errors.js │ ├── location.js │ ├── misc.js │ ├── params.js │ ├── path.js │ ├── push-state.js │ ├── query.js │ ├── resolve-components.js │ ├── route.js │ ├── scroll.js │ ├── state-key.js │ └── warn.js ├── test ├── .eslintrc ├── e2e │ ├── .eslintrc │ ├── browserstack-send-status.js │ ├── nightwatch.browserstack.js │ ├── nightwatch.config.js │ ├── runner.js │ └── specs │ │ ├── .prettierrc │ │ ├── active-links.js │ │ ├── auth-flow.js │ │ ├── basic.js │ │ ├── composables.js │ │ ├── data-fetching.js │ │ ├── hash-mode.js │ │ ├── hash-scroll-behavior.js │ │ ├── history-state.js │ │ ├── keepalive-view.js │ │ ├── lazy-loading-before-mount.js │ │ ├── lazy-loading.js │ │ ├── multi-app.js │ │ ├── named-routes.js │ │ ├── named-views.js │ │ ├── navigation-guards.js │ │ ├── nested-router.js │ │ ├── nested-routes.js │ │ ├── redirect.js │ │ ├── restart-app.js │ │ ├── route-alias.js │ │ ├── route-matching.js │ │ ├── route-params.js │ │ ├── route-props.js │ │ ├── scroll-behavior.js │ │ └── transitions.js └── unit │ ├── .eslintrc │ ├── jasmine.json │ └── specs │ ├── abstract-history.spec.js │ ├── api.spec.js │ ├── async.spec.js │ ├── create-map.spec.js │ ├── create-matcher.spec.js │ ├── custom-query.spec.js │ ├── discrete-components.spec.js │ ├── error-handling.spec.js │ ├── location.spec.js │ ├── node.spec.js │ ├── onReady.spec.js │ ├── path.spec.js │ ├── query.spec.js │ └── route.spec.js ├── types ├── composables.d.ts ├── index.d.ts ├── router.d.ts ├── test │ ├── index.ts │ ├── meta.ts │ └── tsconfig.json └── vue.d.ts ├── vetur ├── attributes.json └── tags.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["env", "flow-vue"], 3 | "plugins": ["syntax-dynamic-import"] 4 | } 5 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | *.ts 3 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "plugins": [ 4 | "flowtype" 5 | ], 6 | "extends": [ 7 | "plugin:vue-libs/recommended", 8 | "plugin:flowtype/recommended" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | .*/node_modules/.* 3 | .*/test/.* 4 | .*/dist/.* 5 | .*/examples/.* 6 | .*/vue/.* 7 | 8 | [include] 9 | 10 | [libs] 11 | flow 12 | 13 | [options] 14 | #unsafe.enable_getters_and_setters=true 15 | suppress_comment= \\(.\\|\n\\)*\\$flow-disable-line 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /.github/funding.yml: -------------------------------------------------------------------------------- 1 | github: [posva, yyx990803] 2 | open_collective: vuejs 3 | -------------------------------------------------------------------------------- /.github/workflows/release-tag.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | tags: 4 | - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 5 | 6 | name: Create Release 7 | 8 | jobs: 9 | build: 10 | name: Create Release 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@master 15 | - name: Create Release for Tag 16 | id: release_tag 17 | uses: yyx990803/release-tag@master 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | with: 21 | tag_name: ${{ github.ref }} 22 | body: | 23 | Please refer to [CHANGELOG.md](https://github.com/vuejs/vue-router/blob/dev/CHANGELOG.md) for details. 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | TODOs.md 4 | test/e2e/reports 5 | test/e2e/screenshots 6 | selenium-debug.log 7 | dist/*.gz 8 | dist/*.map 9 | explorations 10 | docs/.vuepress/dist 11 | yarn-error.log 12 | .idea 13 | .vscode/settings.json 14 | .env 15 | selenium-server.log 16 | local.log 17 | browserstack.err 18 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "printWidth": 80 5 | } 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2013-present Evan You 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /assets/browserstack-logo-600x315.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/assets/browserstack-logo-600x315.png -------------------------------------------------------------------------------- /build/rollup.dev.config.js: -------------------------------------------------------------------------------- 1 | const { input, output } = require('./configs')[0] 2 | 3 | module.exports = Object.assign({}, input, { output }) 4 | -------------------------------------------------------------------------------- /composables.d.ts: -------------------------------------------------------------------------------- 1 | export * from './types/composables' 2 | -------------------------------------------------------------------------------- /docs-gitbook/LANGS.md: -------------------------------------------------------------------------------- 1 | * [English](en/) 2 | * [French](fr/) 3 | * [Japanese](ja/) 4 | * [中文](zh-cn/) 5 | * [German](de/) 6 | * [Русский](ru/) 7 | * [한국어(Korean)](kr/) 8 | * [Español](es/) 9 | * [0.7 Docs](old/) 10 | -------------------------------------------------------------------------------- /docs-gitbook/assets/CNAME: -------------------------------------------------------------------------------- 1 | router.vuejs.org 2 | -------------------------------------------------------------------------------- /docs-gitbook/assets/circle.yml: -------------------------------------------------------------------------------- 1 | general: 2 | branches: 3 | ignore: 4 | - gh-pages 5 | -------------------------------------------------------------------------------- /docs-gitbook/book.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "vue-router", 3 | "gitbook": ">3.0.0", 4 | "plugins": ["edit-link", "theme-vuejs", "-fontsettings", "github"], 5 | "pluginsConfig": { 6 | "edit-link": { 7 | "base": "https://github.com/vuejs/vue-router/edit/dev/docs", 8 | "label": "Edit This Page" 9 | }, 10 | "github": { 11 | "url": "https://github.com/vuejs/vue-router/" 12 | } 13 | }, 14 | "links": { 15 | "sharing": { 16 | "facebook": false, 17 | "twitter": false 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /docs-gitbook/de/README.md: -------------------------------------------------------------------------------- 1 | SUMMARY.md -------------------------------------------------------------------------------- /docs-gitbook/de/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # vue-router 2 | 3 | 4 | > Merke: vue-router@2.x ist nur mit Vue 2.x kompatibel. Dokumentation für 0.7.x ist [hier (englisch)](https://github.com/vuejs/vue-router/tree/1.0/docs/en) 5 | 6 | 7 | **[Versionshinweise (englisch)](https://github.com/vuejs/vue-router/releases)** 8 | 9 | - [Installation](installation.md) 10 | - Grundlegendes 11 | - [Erste Schritte](essentials/getting-started.md) 12 | - [Dynamisches Route-Matching](essentials/dynamic-matching.md) 13 | - [Verschachtelte Routes](essentials/nested-routes.md) 14 | - [Programmatische Navigation](essentials/navigation.md) 15 | - [Benannte Routes](essentials/named-routes.md) 16 | - [Benannte Views](essentials/named-views.md) 17 | - [Redirect und Alias](essentials/redirect-and-alias.md) 18 | - [HTML5-Verlaufsmodus](essentials/history-mode.md) 19 | - Fortgeschritten 20 | - [Navigations-Guards](advanced/navigation-guards.md) 21 | - [Route Meta-Felder](advanced/meta.md) 22 | - [Transitions (Übergänge)](advanced/transitions.md) 23 | - [Daten laden](advanced/data-fetching.md) 24 | - [Scroll-Verhalten](advanced/scroll-behavior.md) 25 | - [Lazy Loading](advanced/lazy-loading.md) 26 | - API-Referenz 27 | - [router-link](api/router-link.md) 28 | - [router-view](api/router-view.md) 29 | - [Das Route-Objekt](api/route-object.md) 30 | - [Router-Option](api/options.md) 31 | - [Router-Instanz](api/router-instance.md) 32 | - [Injection von Komponenten](api/component-injections.md) 33 | -------------------------------------------------------------------------------- /docs-gitbook/de/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # Route Meta-Felder 2 | 3 | In der Route-Definition kann man ein Meta-Feld definieren: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // ein Metafeld 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | Und wie greifen wir auf das `meta`-Feld zu? 25 | 26 | Zunächst einmal: Wir nennen jedes Route-Objekt in der `routes`-Konfiguration **Route-Record**. Route-Records können verschachtelt sein, weshalb eine URL potentiell zu mehreren Route-Records passen kann. 27 | 28 | Zum Beispiel werden mit der obigen Konfiguration und der URL `/foo/bar` beide - Parent-Record und Child-Record - gematched. 29 | 30 | Alle Route-Records, die auf eine URL zutreffen, sind im `$route`-Objekt und in den Route-Objekten in Navigation-Guards im `$route.matched`-Array zu finden. Deswegen müssen wir mit einer Schleife das `$route.matched` Array durchlaufen, um alle Route-Records auf Metafelder zu prüfen. 31 | 32 | Ein Anwendungsfall ist die Prüfung nach einem Metafeld im globalen Before-Guard: 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // Diese Route benötigt Authentifizierung und prüft, 38 | // ob man eingeloggt ist. 39 | // Wenn nicht, Redirect zur Login-Seite. 40 | if (!auth.loggedIn()) { 41 | next({ 42 | path: '/login', 43 | query: { redirect: to.fullPath } 44 | }) 45 | } else { 46 | next() 47 | } 48 | } else { 49 | next() // Rufe immer next() auf. 50 | } 51 | }) 52 | ``` 53 | -------------------------------------------------------------------------------- /docs-gitbook/de/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # Transitions (Übergänge) 2 | 3 | Da `` im Grunde eine dynamische Komponente ist, kann man Übergangs-Effekte mit der ``-Komponente hinzufügen: 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [Alle Features von ``](http://vuejs.org/guide/transitions.html) funktionieren hier genauso. 12 | 13 | ### Übergang für einzelne Routes 14 | 15 | Das obige Beispiel nutzt den gleichen Übergangseffekt für alle Routes. Wenn unterschiedliche Übergänge je Route gewollt sind, kann man `` stattdessen *in* der Route-Komponente mit jeweils anderen Namen verwenden: 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | ### Route-basierter dynamischer Übergang 36 | 37 | Es ist auch möglich, den Übergang dynamisch anhand der Beziehung zwischen Ziel- und aktueller Route festzulegen: 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // überwache $route in der Parent-Komponente, 48 | // um den Übergang festzulegen 49 | watch: { 50 | '$route' (to, from) { 51 | const toDepth = to.path.split('/').length 52 | const fromDepth = from.path.split('/').length 53 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 54 | } 55 | } 56 | ``` 57 | 58 | Komplettes Beispiel [hier](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js) ansehen. 59 | -------------------------------------------------------------------------------- /docs-gitbook/de/api/component-injections.md: -------------------------------------------------------------------------------- 1 | # Injektion von Komponenten 2 | 3 | ### Injizierte Eigenschaften 4 | 5 | Die folgenden Eigenschaften werden in jede Child-Komponente injiziert, wenn man die Router-Instanz in die Root-Instanz der App als `router:`-Option übergibt. 6 | 7 | - #### $router 8 | 9 | Die Router-Instanz. 10 | 11 | - #### $route 12 | 13 | Die aktuell aktive [Route](route-object.md). Diese Eigenschaft ist schreibgeschützt und ihre Eigenschaften sind unveränderbar - aber sie kann überwacht werden. 14 | 15 | ### Aktivierte Optionen 16 | 17 | - **beforeRouteEnter** 18 | - **beforeRouteLeave** 19 | 20 | Siehe [Guards in Komponenten Komponentenschutz](../advanced/navigation-guards.md#guards-in-komponenten). 21 | -------------------------------------------------------------------------------- /docs-gitbook/de/api/router-view.md: -------------------------------------------------------------------------------- 1 | # `` 2 | 3 | Die ``-Komponente ist eine 'functional' Komponente, die die gematchte Komponente zum gegebenen Pfad rendert. Komponenten, die in `router-view` gerendert werden, können auch eigene ``s enthalten, welche dann Komponenten für verschachtelte Pfade rendern. 4 | 5 | ### Props 6 | 7 | - **name** 8 | 9 | - Typ: `string` 10 | 11 | - Default: `"default"` 12 | 13 | Wenn `` einen Namen trägt, rendert es die Komponente mit dem zugehörigen Namen in der `components`-Option in dem gematchten Route-Eintrag. Siehe [Benannte Views](../essentials/named-views.md). 14 | 15 | ### Verhalten 16 | 17 | Alle anderen Props werden an die gerenderte Komponente weitergeleitet, allerdings sind die relevanten Daten je Route meistens in den Route-Parametern vorhanden. 18 | 19 | Da `` auch nur eine normale Komponente ist, funktioniert sie mit `` und ``. Wenn zusammen genutzt, achte darauf dass `` innerhalb der `` ist: 20 | 21 | ``` html 22 | 23 | 24 | 25 | 26 | 27 | ``` 28 | -------------------------------------------------------------------------------- /docs-gitbook/de/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Benannte Routes 2 | 3 | Manchmal ist es einfacher, eine Route mit einem Namen anzusprechen. Besonders bei Links zu einer Route oder dem Ausführen von Navigationen. Den Namen vergibt man beim Erzeugen der Router-Instanz in den `routes`-Optionen: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Um mit `router-link` zu einer benannten Route zu verlinken, gibt man ein Objekt in die `to`-Prop ein: 18 | 19 | ``` html 20 | User 21 | ``` 22 | 23 | Das exakt gleiche Objekt kann auch programmatisch in `router.push()` genutzt werden. 24 | 25 | 26 | ``` js 27 | router.push({ name: 'user', params: { userId: 123 }}) 28 | ``` 29 | 30 | In beiden Fällen wird der Router zum Pfad `/user/123` navigieren. 31 | 32 | Vollständiges Beispiel [hier](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 33 | -------------------------------------------------------------------------------- /docs-gitbook/de/essentials/named-views.md: -------------------------------------------------------------------------------- 1 | # Benannte Views 2 | 3 | Manchmal muss man mehrere Views zur selben Zeit darstellen, anstatt sie zu verschachteln. Zum Beispiel bei einem Layout mit Hauptteil und Seitenleiste. Hier sind benannte Views nützlich. Anstelle eines einzigen Outlets für die View-Darstellung gibt es mehrere, die Namen tragen können. Ein `router-view` ohne Namen heißt standardmäßig `default`. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | Ein View wird durch eine Komponente gerendert, deswegen benötigen mehrere Views auch mehrere Komponenten für dieselbe Route. Dabei ist es wichtig, `components` (Plural) in den Optionen zu verwenden: 12 | 13 | ``` js 14 | const router = new VueRouter({ 15 | routes: [ 16 | { 17 | path: '/', 18 | components: { 19 | default: Foo, 20 | a: Bar, 21 | b: Baz 22 | } 23 | } 24 | ] 25 | }) 26 | ``` 27 | 28 | Eine Demo zu diesem Beispiel ist 29 | [hier](https://jsfiddle.net/posva/6du90epg/) zu finden. 30 | -------------------------------------------------------------------------------- /docs-gitbook/de/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | ### Direkter Download / CDN 4 | 5 | [https://unpkg.com/vue-router](https://unpkg.com/vue-router) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) bietet NPM-basierte CDN-Links an. Der obige Link führt immer zur aktuellsten Version auf NPM. Eine genaue Version kann via URL genutzt werden: `https://unpkg.com/vue-router@2.0.0`. 9 | 10 | 11 | Füge `vue-router` nach Vue ein und es installiert sich automatisch selbst: 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### NPM 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | Wenn ein Module-System genutzt wird (z.B. Webpack, Browserify), muss der Router explizit via `Vue.use()` installiert werden: 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | Wenn globale Skript-Tags genutzt werden ist das nicht notwendig. 34 | 35 | ### Dev Build (Entwicklungs-Version) 36 | 37 | Wenn die aktuelle Dev-Version genutzt werden soll, muss das Repository direkt von GitHub geklont und die aktuelle `vue-router`-Build selbst erstellt werden, . 38 | 39 | 40 | ``` bash 41 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 42 | cd node_modules/vue-router 43 | npm install 44 | npm run build 45 | ``` 46 | -------------------------------------------------------------------------------- /docs-gitbook/es/README.md: -------------------------------------------------------------------------------- 1 | {% include "./SUMMARY.md" %} 2 | -------------------------------------------------------------------------------- /docs-gitbook/es/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # Campos Meta en las rutas 2 | 3 | Puedes incluir un campo `meta` cuando definas una ruta: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // campo meta 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | Entonces, ¿como accedemos al campo `meta`? 25 | 26 | Primero, cada objeto route en la configuración de `routes` se llama **registro de ruta**. Los registros de ruta pueden estar anidados. Por lo tanto, cuando una ruta coincida, existe la posibilidad que lo haga con más de un registro de ruta. 27 | 28 | Por ejemplo, con la configuración anterior, la URL `/foo/bar` coincidirá tanto con el registro de ruta padre como con el hijo. 29 | 30 | Todos los registros de rutas que hayan coincidido son expuestos en el objeto `$route` (y también a los objetos route en las guardias de navegación) como el array `$route.matched`. Por ende, necesitaremos iterar sobre `$route.matched` para verificar campos meta en los registros de rutas. 31 | 32 | Un caso de uso de ejemplo es verificar la existencia de campos metas en los guardias de navegación global: 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // esta ruta requiere autenticación, verificamos que haya iniciado sesión 38 | // sino, redirigimos a la página de inicio de sesión. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // ¡Asegúrate de ejecutar next siempre! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs-gitbook/es/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # Transiciones 2 | 3 | Dado que `` es esencialmente un componente dinámico, podemos aplicarle efectos de transición utilizando el componente ``: 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [Todo acerca de ``](http://vuejs.org/guide/transitions.html) también funciona aquí. 12 | 13 | ### Transiciones por ruta 14 | 15 | El ejemplo anterior aplicará la misma transición a todas las rutas. Si deseas que cada componente de ruta tenga diferentes transiciones, puedes utilizar `` con diferentes nombres dentro de cada componente de ruta: 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | ### Transiciones dinámicas basadas en componentes 36 | 37 | También es posible determinar dinámicamente la transición a utilizar basado en las relaciones entre la ruta destino y la ruta actual: 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // luego, en el componente padre, 48 | // observa $route para determinar que transición utilizar 49 | watch: { 50 | '$route' (to, from) { 51 | const toDepth = to.path.split('/').length 52 | const fromDepth = from.path.split('/').length 53 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 54 | } 55 | } 56 | ``` 57 | 58 | Tienes un ejemplo completo [aquí](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). 59 | -------------------------------------------------------------------------------- /docs-gitbook/es/api/component-injections.md: -------------------------------------------------------------------------------- 1 | # Inyección en componentes 2 | 3 | ### Propiedades inyectadas 4 | 5 | Estas propiedades son inyectadas dentro de cada componente hijo pasando la instancia del `router` a la instancia principal como la opción `router`. 6 | 7 | - #### $router 8 | 9 | La instancia del `router`. 10 | 11 | - #### $route 12 | 13 | El objeto [Route activo](route-object.md). Esta propiedad es de solo lectura y sus propiedades son inmutables, pero puede ser observada. 14 | 15 | ### Opciones habilitadas 16 | 17 | - **beforeRouteEnter** 18 | - **beforeRouteUpdate** (agregado en 2.2) 19 | - **beforeRouteLeave** 20 | 21 | Más información en [guardias en componentes](../advanced/navigation-guards.md#incomponent-guards). 22 | -------------------------------------------------------------------------------- /docs-gitbook/es/api/router-view.md: -------------------------------------------------------------------------------- 1 | # `` 2 | 3 | El componente `` es un componente funcional que renderiza a otro en base a la ruta seleccionada. Los componentes renderizados en `` pueden contener su propio ``, el cual renderizará componentes para sub-rutas. 4 | 5 | ### Propiedades 6 | 7 | - **name** 8 | 9 | - tipo: `string` 10 | 11 | - valor por defecto: `"default"` 12 | 13 | Cuando un componente `` tiene un nombre, renderizará el componente con el nombre correspondiente en la opción `components` del registro de ruta que coincida. Accede a [vistas con nombre](../essentials/named-views.md) para más información. 14 | 15 | ### Comportamiento 16 | 17 | Cualquier propiedad diferente a `name` será pasada al componente renderizado. De cualquier manera, la mayor parte del tiempo los datos de la ruta están contenidos dentro de los parámetros de la ruta. 18 | 19 | Dado que es simplemente un componente, funciona con `` y ``. Cuando utilices ambos en conjunto, asegúrate de usar `` dentro de ``: 20 | 21 | ``` html 22 | 23 | 24 | 25 | 26 | 27 | ``` 28 | -------------------------------------------------------------------------------- /docs-gitbook/es/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Rutas con nombre 2 | 3 | A veces es conveniente identificar una ruta con un nombre, especialmente cuando enlazamos a esa ruta o navegamos mediante código. Puedes darle un nombre a una ruta en las opciones de `routes` cuando se crea la instancia de Router: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Para enlazar a una ruta con nombre, puedes pasar un objeto a la propiedad `to` del componente `router-link`: 18 | 19 | ``` html 20 | User 21 | ``` 22 | 23 | Este es exactamente el mismo objeto utilizado mediante código con `router.push()`: 24 | 25 | ``` js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | En ambos casos, el _router_ navegará a la ruta `/user/123`. 30 | 31 | Revisa un ejemplo completo [aquí](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 32 | -------------------------------------------------------------------------------- /docs-gitbook/es/essentials/named-views.md: -------------------------------------------------------------------------------- 1 | # Vistas con nombre 2 | 3 | A veces es necesario mostrar múltiples vistas al mismo tiempo en lugar de anidarlas. Por ejemplo, cuando se crea una plantilla con una vista `sidebar` y una vista `main`. Aquí es cuando las vistas con nombre se vuelven útiles. En lugar de tener un solo _outlet_ en tu vista, puedes tener varios y darle a cada uno un nombre diferente. Por defecto, un `router-view` sin nombre se llamará `default`. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | Una vista se renderiza utilizando un componente, por lo tanto, múltiples vistas requerirán múltiples componentes para la misma ruta. Asegúrate de utilizar la opción `components` (con una _s_ al final): 12 | 13 | ``` js 14 | const router = new VueRouter({ 15 | routes: [ 16 | { 17 | path: '/', 18 | components: { 19 | default: Foo, 20 | a: Bar, 21 | b: Baz 22 | } 23 | } 24 | ] 25 | }) 26 | ``` 27 | 28 | Puedes ver una demostración de este ejemplo [aquí](https://jsfiddle.net/posva/6du90epg/). 29 | -------------------------------------------------------------------------------- /docs-gitbook/es/installation.md: -------------------------------------------------------------------------------- 1 | # Instalación 2 | 3 | ### Descarga directa / CDN 4 | 5 | [https://unpkg.com/vue-router/dist/vue-router.js](https://unpkg.com/vue-router/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) provee enlaces a CDN basadas en NPM. El enlace anterior siempre apuntará a la última versión en NPM. También puedes usar una versión/etiqueta específica a través de URLs como`https://unpkg.com/vue-router@2.0.0/dist/vue-router.js`. 9 | 10 | 11 | Incluye `vue-router` luego de Vue y se instalará automáticamente: 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### NPM 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | Cuando lo utilices con un sistema de empaquetamiento de módulos, debes instalarlo explícitamente a través de `Vue.use()`: 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | No necesitas hacer esto cuando utilices etiquetas _script_ globales. 34 | 35 | ### Versión de desarrollo 36 | 37 | Debes clonar el repositorio directamente desde GitHub y construir `vue-router` tu mismo si quieres utilizar la última versión de desarrollo. 38 | 39 | ``` bash 40 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 41 | cd node_modules/vue-router 42 | npm install 43 | npm run build 44 | ``` 45 | -------------------------------------------------------------------------------- /docs-gitbook/fr/README.md: -------------------------------------------------------------------------------- 1 | {% include "./SUMMARY.md" %} 2 | -------------------------------------------------------------------------------- /docs-gitbook/fr/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # Champs meta de route 2 | 3 | Vous pouvez inclure un champ `meta` quand vous définissez une route : 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // un champ `meta` 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | Comment maintenant accéder à ce champ `meta` ? 25 | 26 | Tout d'abord, chaque objet route dans la configuration de `routes` est appelé un **registre de route**. Les registres de route peuvent être imbriqués. Par conséquent, quand une route concorde, elle peut potentiellement concorder avec plus d'un registre de route. 27 | 28 | Par exemple, avec la configuration de route ci-dessous, l'URL `/foo/bar` va concorder avec le registre parent et le registre enfant. 29 | 30 | Tous les registres concordants avec une route sont exposés dans l'objet `$route` (ainsi que les objets de route dans les sécurisations de navigation) dans le tableau `$route.matched`. Donc, nous devons itérer à travers `$route.matched` pour vérifier les champs meta dans les registres de route. 31 | 32 | Un exemple concret est la vérification d'un champ meta dans une interception de navigation globale : 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // cette route demande une autorisation, vérifions si l'utilisateur est logué. 38 | // sinon, redirigeons le sur la page de login. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // assurez vous de toujours appeler `next()` ! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs-gitbook/fr/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # Transitions 2 | 3 | Vu que `` est essentiellement un composant dynamique, on peut lui appliquer certains effets de transitions en utilisant le composant `` : 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [Tout à propos de ``](https://fr.vuejs.org/v2/guide/transitions.html) fonctionne également ici de la même manière. 12 | 13 | ### Transition par route 14 | 15 | L'utilisation du dessus applique la même transition pour chaque route. Si vous voulez que les composants de route aient des transitions différentes, vous pouvez utiliser à la place `` avec des noms différents à l'intérieur de chaque composant de route : 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | # Transition dynamique basée sur la route 36 | 37 | Il est aussi possible de déterminer la transition à utiliser en se basant sur la relation entre la route cible et la route actuelle : 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // et dans le composant parent, 48 | // observer la `$route` pour déterminer la transition à utiliser 49 | watch: { 50 | '$route' (to, from) { 51 | const toDepth = to.path.split('/').length 52 | const fromDepth = from.path.split('/').length 53 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 54 | } 55 | } 56 | ``` 57 | 58 | Voir un exemple complet [ici](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). 59 | -------------------------------------------------------------------------------- /docs-gitbook/fr/api/component-injections.md: -------------------------------------------------------------------------------- 1 | # Injections de composant 2 | 3 | ### Propriétés injectées 4 | 5 | Ces propriétés sont injectées dans chacun des composants enfants, en passant l'instance du routeur à l'application racine de Vue en tant qu'option `router`. 6 | 7 | - #### $router 8 | 9 | L'instance du routeur. 10 | 11 | - #### $route 12 | 13 | La [Route](route-object.md) actuellement active. C'est une propriété en lecture seule et ses propriétés sont immutables, mais elles restent malgré tout observables. 14 | 15 | ### Options activées 16 | 17 | - **beforeRouteEnter** 18 | - **beforeRouteUpdate** (ajouté en 2.2) 19 | - **beforeRouteLeave** 20 | 21 | Voir l'[interception par composant](../advanced/navigation-guards.md#securisation-par-composant). 22 | -------------------------------------------------------------------------------- /docs-gitbook/fr/api/router-view.md: -------------------------------------------------------------------------------- 1 | # `` 2 | 3 | Le composant `` est un composant fonctionnel qui fait le rendu du composant correspondant au chemin donné. Les composants rendus dans `` peuvent aussi contenir leur propre ``, qui fera le rendu des composants pour les chemins imbriqués. 4 | 5 | ### Props 6 | 7 | - **name** 8 | 9 | - type : `string` 10 | 11 | - défaut : `"default"` 12 | 13 | Lorsqu'un `` a un nom, il fera le rendu du composant correspondant à ce nom dans les itinéraires de route correspondant à l'option `components`. Voir les [Routes nommées](../essentials/named-views.md) pour un exemple. 14 | 15 | ### Comportement 16 | 17 | Les propriétés sans nom seront passées le long du composant rendu, toutefois la plupart du temps, les données par route seront contenues dans les paramètres de la route. 18 | 19 | Car c'est juste un composant, il fonctionne avec `` et ``. Lorsque vous utilisez les deux ensemble, soyez sûr d'utiliser ` à l'intérieur : 20 | 21 | ``` html 22 | 23 | 24 | 25 | 26 | 27 | ``` 28 | -------------------------------------------------------------------------------- /docs-gitbook/fr/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Routes nommées 2 | 3 | Parfois il est plus pratique d'identifier une route avec un nom, tout particulièrement quand on souhaite attacher cette route ou exécuter des actions de navigation. Vous pouvez donner un nom à une route dans les options `routes` pendant la création de l'instance du routeur : 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/utilisateur/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Pour attacher une route nommée, vous pouvez passer un objet à la prop `to` du composant `router-link` : 18 | 19 | ``` html 20 | Utilisateur 21 | ``` 22 | 23 | C'est exactement le même objet à utiliser programmatiquement avec `router.push()` : 24 | 25 | ``` js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | Dans les deux cas, le routeur va naviguer vers le chemin `/utilisateur/123`. 30 | 31 | Un exemple complet se trouve [ici](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 32 | -------------------------------------------------------------------------------- /docs-gitbook/fr/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | ### Téléchargement direct / CDN 4 | 5 | [https://unpkg.com/vue-router/dist/vue-router.js](https://unpkg.com/vue-router/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) fournit des liens CDN basés sur npm. Le lien ci-dessus pointera toujours vers la dernière version sur npm. Vous pouvez aussi utiliser un tag ou une version spécifique via un URL comme `https://unpkg.com/vue-router@2.0.0/dist/vue-router.js`. 9 | 10 | 11 | Incluez `vue-router` après Vue et l'installation sera automatique : 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### npm 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | Lorsqu'il est utilisé avec un système de module, vous devez explicitement installer le router via `Vue.use()` : 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | Vous n'avez pas besoin de faire cela lors de l'utilisation des balises de script globales (` 15 | 16 | ``` 17 | 18 | ### npm 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | モジュールシステムを使う場合、`Vue.use()` を使って明示的にルーターをインストールする必要があります。 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | グローバルな script タグを使っている場合は必要ありません。 34 | 35 | ### 開発用ビルド 36 | 37 | もし最新の開発用ビルドを使用したい場合は、GitHub から直接クローンして `vue-router` をご自身でビルドしてください。 38 | 39 | ``` bash 40 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 41 | cd node_modules/vue-router 42 | npm install 43 | npm run build 44 | ``` 45 | -------------------------------------------------------------------------------- /docs-gitbook/kr/README.md: -------------------------------------------------------------------------------- 1 | {% include "./SUMMARY.md" %} 2 | -------------------------------------------------------------------------------- /docs-gitbook/kr/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # vue-router 2 | 3 | > 참고 : vue-router@2.x는 Vue 2.x에서만 작동합니다. 0.7.x용 문서는 [이 곳](https://github.com/vuejs/vue-router/tree/1.0/docs/en)입니다. 4 | 5 | **[릴리즈 노트](https://github.com/vuejs/vue-router/releases)** 6 | 7 | - [설치](installation.md) 8 | - 필수 사항 9 | - [시작하기](essentials/getting-started.md) 10 | - [동적 라우트 매칭](essentials/dynamic-matching.md) 11 | - [중첩된 라우트](essentials/nested-routes.md) 12 | - [프로그래밍 방식 네비게이션](essentials/navigation.md) 13 | - [이름을 가진 라우트](essentials/named-routes.md) 14 | - [이름을 가진 뷰](essentials/named-views.md) 15 | - [리다이렉트와 별칭](essentials/redirect-and-alias.md) 16 | - [라우트 컴포넌트에 속성 전달](essentials/passing-props.md) 17 | - [HTML5 History 모드](essentials/history-mode.md) 18 | - 고급 19 | - [네비게이션 가드](advanced/navigation-guards.md) 20 | - [라우트 메타 필드](advanced/meta.md) 21 | - [전환](advanced/transitions.md) 22 | - [데이터 가져오기](advanced/data-fetching.md) 23 | - [스크롤 동작](advanced/scroll-behavior.md) 24 | - [지연된 로딩](advanced/lazy-loading.md) 25 | - API 레퍼런스 26 | - [라우터 생성자 옵션](api/options.md) 27 | - [routes](api/options.md#routes) 28 | - [mode](api/options.md#mode) 29 | - [base](api/options.md#base) 30 | - [linkActiveClass](api/options.md#linkactiveclass) 31 | - [linkExactActiveClass](api/options.md#linkexactactiveclass) 32 | - [scrollBehavior](api/options.md#scrollbehavior) 33 | - [parseQuery / stringifyQuery](api/options.md#parsequery--stringifyquery) 34 | - [fallback](api/options.md#fallback) 35 | - [라우터 인스턴스](api/router-instance.md) 36 | - [Properties](api/router-instance.md#properties) 37 | - [Methods](api/router-instance.md#methods) 38 | - [라우트 객체](api/route-object.md) 39 | - [컴포넌트 주입](api/component-injections.md) 40 | - [router-link](api/router-link.md) 41 | - [router-view](api/router-view.md) 42 | -------------------------------------------------------------------------------- /docs-gitbook/kr/advanced/lazy-loading.md: -------------------------------------------------------------------------------- 1 | # 지연된 로딩 2 | 3 | 번들러를 이용하여 앱을 제작할 때 JavaScript 번들이 상당히 커져 페이지로드 시간에 영향을 줄 수 있습니다. 각 라우트의 컴포넌트를 별도의 단위로 분할하고 경로를 방문할 때 로드하는 것이 효율적일 것입니다. 4 | 5 | Vue의 [비동기 컴포넌트](http://vuejs.org/guide/components.html#Async-Components)와 Webpack의 [코드 분할](https://webpack.js.org/guides/code-splitting-async/)을 결합합니다. 라우트 컴포넌트를 쉽게 불러올 수 있습니다. 6 | 7 | 첫째, 비동기 컴포넌트는 Promise를 반환하는 팩토리 함수로 정의할 수 있습니다 (컴포넌트가 resolve 되어야함). 8 | 9 | ``` js 10 | const Foo = () => Promise.resolve({ /* 컴포넌트 정의 */ }) 11 | ``` 12 | 13 | 둘째, Webpack 2에서 [dynamic import](https://github.com/tc39/proposal-dynamic-import)를 사용하여 코드 분할 포인트를 지정할 수 있습니다. 14 | 15 | ``` js 16 | import('./Foo.vue') // returns a Promise 17 | ``` 18 | 19 | > 참고: Babel을 사용하고 있는 경우 올바른 구문 분석을 위해 [syntax-dynamic-import](http://babeljs.io/docs/plugins/syntax-dynamic-import/) 플러그인을 추가해야합니다. 20 | 21 | 이 두 가지를 결합하여 Webpack에 의해 자동으로 코드 분할될 비동기 컴포넌트를 정의하는 방법입니다. 22 | 23 | ``` js 24 | const Foo = () => import('./Foo.vue') 25 | ``` 26 | 27 | 라우트 설정에서 아무것도 바꿀 필요가 없습니다. `Foo`만 사용하면 됩니다. 28 | 29 | ``` js 30 | const router = new VueRouter({ 31 | routes: [ 32 | { path: '/foo', component: Foo } 33 | ] 34 | }) 35 | ``` 36 | 37 | ### 같은 묶음으로 컴포넌트 그룹화하기 38 | 39 | 때로는 동일한 라우트 아래에 중첩된 모든 컴포넌트를 동일한 비동기 묶음으로 그룹화 할 수 있습니다. 이를 위해 특수 주석 문법을 사용하는 이름(Webpack 2.4 이상 지원)을 제공하여 [이름을 가진 묶음](https://webpack.js.org/guides/code-splitting-async/#chunk-names)을 사용해야합니다. 40 | 41 | ``` js 42 | const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') 43 | const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') 44 | const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') 45 | ``` 46 | 47 | Webpack은 동일한 이름의 묶음을 가진 비동기 모듈을 동일한 비동기 묶음으로 그룹화합니다. 48 | -------------------------------------------------------------------------------- /docs-gitbook/kr/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # 라우트 메타 필드 2 | 3 | 라우트를 정의 할 때 `meta` 필드를 포함시킬 수 있습니다. 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // 메타 필드 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | 그렇다면 이 `메타`필드에 어떻게 접근할까요? 25 | 26 | 첫째,`routes` 설정의 각 라우트 객체를 **라우트 레코드** 라고합니다. 라우트 레코드는 중첩 될 수 있습니다. 따라서 라우트가 일치하면 둘 이상의 라우트 레코드와 잠재적으로 일치 할 수 있습니다. 27 | 28 | 예를 들어, 위의 라우트 구성에서 URL `/foo/bar`는 상위 라우트 레코드와 하위 라우트 레코드 모두와 일치합니다. 29 | 30 | 라우트와 일치하는 모든 라우트 레코드는 `$route` 객체(그리고 네비게이션 가드의 라우트 객체)에 `$route.matched` 배열로 노출됩니다. 그러므로 우리는 `$route.matched`를 반복하여 라우트 레코드의 메타 필드를 검사 할 필요가 있습니다. 31 | 32 | 예제 사용 사례는 글로벌 네비게이션 가드에서 메타 필드를 확인하는 것입니다. 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // 이 라우트는 인증이 필요하며 로그인 한 경우 확인하십시오. 38 | // 그렇지 않은 경우 로그인 페이지로 리디렉션하십시오. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // 반드시 next()를 호출하십시오! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs-gitbook/kr/advanced/scroll-behavior.md: -------------------------------------------------------------------------------- 1 | # 스크롤 동작 2 | 3 | 클라이언트 측 라우팅을 사용할 때 새로운 경로로 이동할 때 맨 위로 스크롤하거나 실제 페이지를 다시 로드하는 것처럼 컨텐츠 항목의 스크롤 위치를 유지할 수 있습니다. `vue-router`는 이러한 것들을 할 수 있으며, 라우트 탐색에서 스크롤 동작을 완전히 사용자 정의할 수 있게합니다. 4 | 5 | **참고: 이 기능은 HTML5 히스토리 모드에서만 작동합니다.** 6 | 7 | 라우터 인스턴스를 생성 할 때 `scrollBehavior` 함수를 제공 할 수 있습니다. 8 | 9 | ``` js 10 | const router = new VueRouter({ 11 | routes: [...], 12 | scrollBehavior (to, from, savedPosition) { 13 | // 원하는 위치로 돌아가기 14 | } 15 | }) 16 | ``` 17 | 18 | `scrollBehavior` 함수는 `to`와 `from` 라우트 객체를받습니다. 세 번째 전달인자인 `savedPosition`은 브라우저의 뒤로/앞으로 버튼으로 트리거되는 `popstate` 네비게이션인 경우에만 사용할 수 있습니다. 19 | 20 | 이 함수는 스크롤 위치 객체를 반환 할 수 있습니다. 객체는 다음과 같은 형태 일 수 있습니다. 21 | 22 | - `{ x: number, y: number }` 23 | - `{ selector: string, offset? : { x: number, y: number }}` (offset은 2.6.0 이상만 지원) 24 | 25 | 잘못된 값이나 빈 객체가 반환되면 스크롤이 발생하지 않습니다. 26 | 27 | 예제: 28 | 29 | ``` js 30 | scrollBehavior (to, from, savedPosition) { 31 | return { x: 0, y: 0 } 32 | } 33 | ``` 34 | 35 | 그러면 모든 라우트 네비게이션에 대해 페이지가 맨 위로 스크롤됩니다. 36 | 37 | `savedPosition`을 반환하면 뒤로/앞으로 버튼으로 탐색할 때 네이티브와 같은 동작이 발생합니다. 38 | 39 | ``` js 40 | scrollBehavior (to, from, savedPosition) { 41 | if (savedPosition) { 42 | return savedPosition 43 | } else { 44 | return { x: 0, y: 0 } 45 | } 46 | } 47 | ``` 48 | 49 | "anchor로 스크롤" 동작을 시뮬레이트하려면 다음을 수행하십시오. 50 | 51 | ``` js 52 | scrollBehavior (to, from, savedPosition) { 53 | if (to.hash) { 54 | return { 55 | selector: to.hash 56 | // , offset: { x: 0, y: 10 } 57 | } 58 | } 59 | } 60 | ``` 61 | 62 | 또한 [라우트 메타 필드](meta.md)를 사용하여 세밀한 스크롤 동작 제어를 구현할 수 있습니다. 전체 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js)를 확인하십시오. 63 | -------------------------------------------------------------------------------- /docs-gitbook/kr/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # 전환 2 | 3 | ``는 본질적으로 동적인 컴포넌트이기 때문에 `` 컴포넌트를 사용하는 것과 같은 방식으로 전환 효과를 적용할 수 있습니다. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [``에 대한 모든 것](http://vuejs.org/guide/transitions.html) 을 확인하십시오. 12 | 13 | ### 라우트 별 전환 14 | 15 | 위의 사용법은 모든 라우트에 대해 동일한 전환을 적용합니다. 각 라우트의 컴포넌트가 서로 다른 전환을 갖도록 하려면 각 라우트 컴포넌트 내에서 다른 이름으로 ``을 사용할 수 있습니다. 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | ### 라우트 기반 동적 전환 36 | 37 | 또한 대상 라우트와 현재 라우트 간의 관계를 기반으로 동적으로 사용할 전환을 결정할 수도 있습니다. 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // 그런 다음 부모 구성 요소에서 `$route`를 보고 사용할 전환을 결정합니다 48 | watch: { 49 | '$route' (to, from) { 50 | const toDepth = to.path.split('/').length 51 | const fromDepth = from.path.split('/').length 52 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 53 | } 54 | } 55 | ``` 56 | 57 | 전체 예제는 [여기](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js)에 있습니다. 58 | -------------------------------------------------------------------------------- /docs-gitbook/kr/api/component-injections.md: -------------------------------------------------------------------------------- 1 | # 컴포넌트 주입 2 | 3 | ### 주입된 속성 4 | 5 | 이러한 프로퍼티는 라우터 인스턴스를 루트 인스턴스에 `router` 옵션으로 전달함으로써 모든 자식 컴포넌트에 주입됩니다. 6 | 7 | - #### $router 8 | 9 | 라우터 인스턴스 10 | 11 | - #### $route 12 | 13 | 현재 활성화 된 [Route](route-object.md)입니다. 이 속성은 읽기 전용이며 해당 속성은 변경할 수는 없지만 감시 할 수 있습니다. 14 | 15 | ### 활성화된 옵션 16 | 17 | - **beforeRouteEnter** 18 | - **beforeRouteUpdate** (2.2에서 추가됨) 19 | - **beforeRouteLeave** 20 | 21 | [컴포넌트 내부 가드](../advanced/navigation-guards.md#incomponent-guards)를 확인하세요. 22 | -------------------------------------------------------------------------------- /docs-gitbook/kr/api/router-view.md: -------------------------------------------------------------------------------- 1 | # `` 2 | 3 | `` 컴포넌트는 주어진 라우트에 대해 일치하는 컴포넌트를 렌더링하는 함수형 컴포넌트입니다. ``에서 렌더링된 컴포넌트는 자체 ``를 포함 할 수 있으며, 이는 중첩 된 라우트를 위해 컴포넌트를 렌더링합니다. 4 | 5 | ### Props 6 | 7 | - **name** 8 | 9 | - 자료형: `string` 10 | 11 | - 기본값: `"default"` 12 | 13 | ``가 이름을 가지고있을 때, 그것은 일치된 라우트 레코드의 `components` 옵션에서 해당 이름으로 컴포넌트를 렌더링 할 것입니다. 예제는 [이름을 가지는 뷰](../essentials/named-views.md)를 참조하십시오. 14 | 15 | ### 동작 16 | 17 | 이름이없는 모든 props는 렌더링된 컴포넌트로 전달되지만 대부분의 경우 라우트 별 데이터는 라우트 매개 변수에 포함됩니다. 18 | 19 | 이것은 단지 컴포넌트이므로 `` 및 ``와 함께 작동합니다. 양쪽 모두를 사용할 때는 ``를 다음과 같이 사용하십시오. 20 | 21 | ``` html 22 | 23 | 24 | 25 | 26 | 27 | ``` 28 | -------------------------------------------------------------------------------- /docs-gitbook/kr/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # 이름을 가지는 라우트 2 | 3 | 때로는 라우트에 연결하거나 탐색을 수행 할 때 이름이 있는 라우트를 사용하는 것이 더 편리합니다. Router 인스턴스를 생성하는 동안 `routes` 옵션에 라우트를 지정할 수 있습니다. 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | 이름을 가진 라우트에 링크하려면, 객체를 `router-link`, 컴포넌트의 `to` prop로 전달할 수 있습니다. 18 | 19 | ``` html 20 | User 21 | ``` 22 | 23 | 이것은 `router.push()`와 프로그램적으로 사용되는 것과 정확히 같은 객체입니다. 24 | 25 | ```js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | 두 경우 모두 라우터는 `/user/123` 경로로 이동합니다. 30 | 31 | 전체 예제는 [여기](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js)에 있습니다. 32 | -------------------------------------------------------------------------------- /docs-gitbook/kr/essentials/named-views.md: -------------------------------------------------------------------------------- 1 | # 이름을 가지는 뷰 2 | 3 | 때로는 여러 개의 뷰를 중첩하지 않고 동시에 표시해야 하는 경우가 있습니다. `sidebar` 뷰와 `main` 뷰로 레이아웃을 생성합니다. 이름이 지정된 뷰가 편리한 경우 입니다. 뷰에 하나의 outlet이 있는 대신 여러 개를 사용하여 각 outlet에 이름을 지정할 수 있습니다. 이름이 없는 `router-view`는 이름으로 `default`가 주어집니다. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | 뷰는 컴포넌트를 사용하여 렌더링 되므로 여러 뷰에는 동일한 라우트에 대해 여러 컴포넌트가 필요합니다. `components`(s를 붙입니다) 옵션을 사용해야합니다. 12 | 13 | ``` js 14 | const router = new VueRouter({ 15 | routes: [ 16 | { 17 | path: '/', 18 | components: { 19 | default: Foo, 20 | a: Bar, 21 | b: Baz 22 | } 23 | } 24 | ] 25 | }) 26 | ``` 27 | 28 | 이 예제는 [여기](https://jsfiddle.net/posva/6du90epg/)에서 확인할 수 있습니다. 29 | -------------------------------------------------------------------------------- /docs-gitbook/kr/essentials/passing-props.md: -------------------------------------------------------------------------------- 1 | # 라우트 컴포넌트에 속성 전달 2 | 3 | 컴포넌트에서 `$route`를 사용하면 특정 URL에서만 사용할 수 있는 컴포넌트의 유연성을 제한하는 라우트와 강한 결합을 만듭니다. 4 | 5 | 컴포넌트와 라우터 속성을 분리하려면 다음과 같이 하십시오. 6 | 7 | ** $route에 의존성 추가** 8 | 9 | ``` js 10 | const User = { 11 | template: '
User {{ $route.params.id }}
' 12 | } 13 | const router = new VueRouter({ 14 | routes: [ 15 | { path: '/user/:id', component: User } 16 | ] 17 | }) 18 | ``` 19 | 20 | ** 속성에 의존성 해제** 21 | 22 | ``` js 23 | const User = { 24 | props: ['id'], 25 | template: '
User {{ id }}
' 26 | } 27 | const router = new VueRouter({ 28 | routes: [ 29 | { path: '/user/:id', component: User, props: true }, 30 | ] 31 | }) 32 | ``` 33 | 34 | 이를 통해 어디서나 컴포넌트를 사용할 수 있으므로 컴포넌트 재사용 및 테스트하기가 더 쉽습니다. 35 | 36 | ### Boolean 모드 37 | 38 | `props`를 `true`로 설정하면 `route.params`가 컴포넌트 `props`로 설정됩니다. 39 | 40 | ### 객체 모드 41 | 42 | `props`가 객체일때 컴포넌트 `props`가 있는 그대로 설정됩니다. 43 | `props`가 정적일 때 유용합니다. 44 | 45 | ``` js 46 | const router = new VueRouter({ 47 | routes: [ 48 | { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } } 49 | ] 50 | }) 51 | ``` 52 | 53 | ### 함수 모드 54 | 55 | `props`를 반환하는 함수를 만들 수 있습니다. 이를 통해 전달인자를 다른 타입으로 캐스팅하고 적정인 값을 라우트 기반 값과 결합됩니다. 56 | 57 | ``` js 58 | const router = new VueRouter({ 59 | routes: [ 60 | { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) } 61 | ] 62 | }) 63 | ``` 64 | 65 | `/search?q=vue`는 `{query: "vue"}`를 `SearchUser` 컴포넌트에 전달합니다. 66 | 67 | 라우트 변경시에만 평가되므로 `props` 함수는 상태를 저장하지 않도록 합니다. 68 | `props`를 정의할 상태가 필요한 경우 래퍼 컴포넌트를 사용하면 상태가 변경될 때마다 응답할 수 있습니다. 69 | 70 | 고급 사용예를 보려면 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js)를 확인하세요. 71 | -------------------------------------------------------------------------------- /docs-gitbook/kr/essentials/redirect-and-alias.md: -------------------------------------------------------------------------------- 1 | # 리다이렉트와 별칭 2 | 3 | ### 리다이렉트 4 | 5 | 리디렉션은 `routes` 설정에서도 할 수 있습니다. `/a`에서 `/b`로 리디렉션하려면 6 | 7 | ``` js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { path: '/a', redirect: '/b' } 11 | ] 12 | }) 13 | ``` 14 | 15 | 리디렉션은 이름이 지정된 라우트를 지정할 수도 있습니다. 16 | 17 | ``` js 18 | const router = new VueRouter({ 19 | routes: [ 20 | { path: '/a', redirect: { name: 'foo' }} 21 | ] 22 | }) 23 | ``` 24 | 25 | 또는 동적 리디렉션을 위한 함수를 사용할 수도 있습니다. 26 | 27 | ``` js 28 | const router = new VueRouter({ 29 | routes: [ 30 | { path: '/a', redirect: to => { 31 | // 함수는 인수로 대상 라우트를 받습니다. 32 | // 여기서 path/location 반환합니다. 33 | }} 34 | ] 35 | }) 36 | ``` 37 | 기타 고급 사용법은 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js)를 확인 하십시오. 38 | 39 | ### 별칭 40 | 41 | 리다이렉트는 사용자가 `/a`를 방문했을 때 URL이 `/b`로 대체 된 다음 `/b`로 매칭된다는 것을 의미합니다. 하지만 별칭이란 무엇입니까? 42 | 43 | **`/a`의 별칭은 `/b`는 사용자가 `/b`를 방문했을 때 URL은 `/b`을 유지하지만 사용자가 `/a`를 방문한 것처럼 매칭합니다.** 44 | 45 | 위는 라우트 구성에서 다음과 같이 표현할 수 있습니다. 46 | 47 | ``` js 48 | const router = new VueRouter({ 49 | routes: [ 50 | { path: '/a', component: A, alias: '/b' } 51 | ] 52 | }) 53 | ``` 54 | 55 | 별칭을 사용하면 구성의 중첩 구조에 의해 제약을 받는 대신 UI 구조를 임의의 URL에 매핑 할 수 있습니다. 56 | 57 | 기타 고급 사용법은 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js)를 확인 하십시오. 58 | -------------------------------------------------------------------------------- /docs-gitbook/kr/installation.md: -------------------------------------------------------------------------------- 1 | # 설치 2 | 3 | ### 직접 다운로드 / CDN 4 | 5 | [https://unpkg.com/vue-router/dist/vue-router.js](https://unpkg.com/vue-router/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com)은 NPM 기반 CDN 링크를 제공합니다. 위의 링크는 항상 NPM의 최신 릴리스를 가리킵니다. `https://unpkg.com/vue-router@2.0.0/dist/vue-router.js`와 같이 URL을 통해 특정 버전 / 태그를 사용할 수도 있습니다. 9 | 10 | 11 | Vue 다음에 `vue-router`를 포함하면 자동으로 설치됩니다. 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### NPM 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | 모듈 시스템에서 사용하면 `Vue.use()`를 통해 명시적으로 라우터를 추가해야합니다. 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | 전역 스크립트 태그를 사용할 때는 이 작업을 하지 않아도 됩니다. 34 | 35 | ### 개발용 빌드 36 | 37 | 최신 dev 빌드를 사용하고 싶은 경우 GitHub에서 직접 복제하고 `vue-router`를 직접 빌드 해야 합니다. 38 | 39 | ``` bash 40 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 41 | cd node_modules/vue-router 42 | npm install 43 | npm run build 44 | ``` 45 | -------------------------------------------------------------------------------- /docs-gitbook/old/README.md: -------------------------------------------------------------------------------- 1 | # 0.7 Docs 2 | 3 | - [English](https://github.com/vuejs/vue-router/tree/1.0/docs/en) 4 | - [Chinese](https://github.com/vuejs/vue-router/tree/1.0/docs/zh-cn) 5 | - [Japanese](https://github.com/vuejs/vue-router/tree/1.0/docs/ja) 6 | -------------------------------------------------------------------------------- /docs-gitbook/old/SUMMARY.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs-gitbook/old/SUMMARY.md -------------------------------------------------------------------------------- /docs-gitbook/ru/README.md: -------------------------------------------------------------------------------- 1 | {% include "./SUMMARY.md" %} 2 | -------------------------------------------------------------------------------- /docs-gitbook/ru/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # Метаданные путей 2 | 3 | При определении пути можно указывать метаданные в поле `meta`: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // метаданные 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | Как получить к нему доступ? 25 | 26 | Прежде всего, каждый объект пути в конфигурации `routes` называется **записью пути**. Записи путей могут быть вложенными. Поэтому, при совпадении пути, потенциально могут быть активированы несколько записей путей. 27 | 28 | Например, для конфигурации выше, URL `/foo/bar` совпадёт как с родительской, так и с дочерней записями путей. 29 | 30 | Все совпавшие записи путей оказываются доступны через объект `$route` (а также через объекты пути в сторожевых хуках), в виде массива `$route.matched`. Таким образом, для проверки метаданных в записях путей нам понадобится обойти `$route.matched` в цикле. 31 | 32 | В качестве примера можно привести проверку метаданных в глобальном сторожевом хуке: 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // этот путь требует авторизации, проверяем залогинен ли 38 | // пользователь, и если нет, перенаправляем на страницу логина 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // всегда так или иначе нужно вызвать next()! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs-gitbook/ru/api/component-injections.md: -------------------------------------------------------------------------------- 1 | # Интеграция с компонентами Vue 2 | 3 | ### Добавляемые свойства 4 | 5 | Перечисленные ниже свойства становятся доступными в каждом дочернем компоненте при передаче роутера через опцию `router` корневого экземпляра приложения. 6 | 7 | - #### $router 8 | 9 | Экземпляр роутера. 10 | 11 | - #### $route 12 | 13 | Объект [Route](route-object.md), соответствующий текущему активному пути. Это свойство доступно только на чтение и его параметры иммутабельны, но над ними можно установить наблюдение. 14 | 15 | ### Доступные опции 16 | 17 | - **beforeRouteEnter** 18 | - **beforeRouteUpdate** (добавлено в версии 2.2) 19 | - **beforeRouteLeave** 20 | 21 | См. [раздел документации о сторожевых хуках](../advanced/navigation-guards.md#указание-хука-для-конкретного-компонента). 22 | -------------------------------------------------------------------------------- /docs-gitbook/ru/api/router-view.md: -------------------------------------------------------------------------------- 1 | # `` 2 | 3 | `` — это функциональный компонент, отображающий соответствующее текущему пути представление. Компоненты, отображаемые на месте `` могут сами содержать вложенные ``, что позволяет организовать иерархию вложенных путей. 4 | 5 | 6 | ### Входные параметры 7 | 8 | - **name** 9 | 10 | - тип: `string` 11 | 12 | - значение по умолчанию: `"default"` 13 | 14 | Если для `` указывается имя, на его месте отобразится компонент, для которого в записи пути указано соответствующее имя в опции `components`. Для подробностей и примера см. [именованные представления](../essentials/named-views.md). 15 | 16 | 17 | ### Поведение 18 | 19 | Все остальные входные параметры будут напрямую переданы отображаемому компоненту представления. Тем не менее, чаще всего данные уровня пути содержатся в параметрах пути (`$route.params`). 20 | 21 | Поскольку мы имеем дело всего лишь с обыкновенным компонентом, можно использовать обёртки `` и ``. Если вы используете оба, удостоверьтесь, что `` располагается внутри: 22 | 23 | ``` html 24 | 25 | 26 | 27 | 28 | 29 | ``` 30 | -------------------------------------------------------------------------------- /docs-gitbook/ru/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Именованные пути 2 | 3 | Зачастую, при создании ссылок и вызове навигационных методов, удобно ссылаться на путь по его имени. Установить имя пути можно в опциях `routes` при создании экземпляра Router'а: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Чтобы создать ссылку на именованный маршрут, вы можете передать объект в компонент `router-link` используя входной параметр `to`: 18 | 19 | ``` html 20 | Пользователь 21 | ``` 22 | 23 | Тот же самый объект можно использовать и для императивного вызова `router.push()`: 24 | 25 | ``` js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | В обоих случаях результатом будет навигационный переход на `/user/123`. 30 | 31 | Полный пример находится [здесь](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 32 | -------------------------------------------------------------------------------- /docs-gitbook/ru/installation.md: -------------------------------------------------------------------------------- 1 | # Установка 2 | 3 | ### Локальный файл / CDN 4 | 5 | [https://unpkg.com/vue-router/dist/vue-router.js](https://unpkg.com/vue-router/dist/vue-router.js) 6 | 7 | [Unpkg.com](https://unpkg.com) предоставляет CDN-ссылки для NPM-пакетов. Ссылка выше всегда указывает на самую последнюю версию Vue-router на NPM. Вы также можете использовать конкретную версию используя ссылки вида `https://unpkg.com/vue-router@2.0.0/dist/vue-router.js`. 8 | 9 | Подключите `Vue-router` после Vue, и установка произойдёт автоматически: 10 | 11 | ``` html 12 | 13 | 14 | ``` 15 | 16 | ### NPM 17 | 18 | ``` bash 19 | npm install vue-router 20 | ``` 21 | 22 | При использовании модульной системы сборки, необходимо явно обозначить использование роутера при помощи `Vue.use()`: 23 | 24 | ``` js 25 | import Vue from 'vue' 26 | import VueRouter from 'vue-router' 27 | 28 | Vue.use(VueRouter) 29 | ``` 30 | 31 | Это не требуется при подключении через глобальный тег `script`. 32 | 33 | ### Сборка версии, находящейся в разработке 34 | 35 | Если вы хотите использовать версию `Vue-router` в разработке, склонируйте репозиторий с GitHub и выполните сборку вручную: 36 | 37 | ``` bash 38 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 39 | cd node_modules/vue-router 40 | npm install 41 | npm run build 42 | ``` 43 | -------------------------------------------------------------------------------- /docs/.vuepress/components/HomeSponsorsGroup.vue: -------------------------------------------------------------------------------- 1 | 19 | 20 | 44 | -------------------------------------------------------------------------------- /docs/.vuepress/components/sponsors.json: -------------------------------------------------------------------------------- 1 | { 2 | "platinum": [], 3 | "gold": [], 4 | "silver": [ 5 | { 6 | "href": "https://www.vuemastery.com/", 7 | "alt": "VueMastery", 8 | "imgSrcLight": "https://posva-sponsors.pages.dev/logos/vuemastery-light.svg", 9 | "imgSrcDark": "https://posva-sponsors.pages.dev/logos/vuemastery-dark.png" 10 | }, 11 | { 12 | "href": "https://www.prefect.io/", 13 | "imgSrcLight": "https://posva-sponsors.pages.dev/logos/prefectlogo-light.svg", 14 | "imgSrcDark": "https://posva-sponsors.pages.dev/logos/prefectlogo-dark.svg", 15 | "alt": "Prefect" 16 | } 17 | ], 18 | "bronze": [ 19 | { 20 | "alt": "Stanislas Ormières", 21 | "href": "https://stormier.ninja", 22 | "imgSrcDark": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4", 23 | "imgSrcLight": "https://avatars.githubusercontent.com/u/2486424?u=7b0c73ae5d090ce53bf59473094e9606fe082c59&v=4" 24 | }, 25 | { 26 | "alt": "Antony Konstantinidis", 27 | "href": "https://www.vuejs.de", 28 | "imgSrcDark": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4", 29 | "imgSrcLight": "https://avatars.githubusercontent.com/u/4183726?u=6b50a8ea16de29d2982f43c5640b1db9299ebcd1&v=4" 30 | }, 31 | { 32 | "href": "https://storyblok.com", 33 | "imgSrcLight": "https://posva-sponsors.pages.dev/logos/storyblok.png", 34 | "imgSrcDark": "https://posva-sponsors.pages.dev/logos/storyblok.png", 35 | "alt": "Storyblok" 36 | }, 37 | { 38 | "href": "https://nuxtjs.org", 39 | "imgSrcLight": "https://posva-sponsors.pages.dev/logos/nuxt-light.svg", 40 | "imgSrcDark": "https://posva-sponsors.pages.dev/logos/nuxt-dark.svg", 41 | "alt": "Nuxt Labs" 42 | } 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /docs/.vuepress/public/_redirects: -------------------------------------------------------------------------------- 1 | # redirect old urls to root 2 | 3 | /en/essentials/getting-started.html /guide/ 4 | /en/essentials/* /guide/essentials/:splat 5 | /en/advanced/* /guide/advanced/:splat 6 | /en/api/* /api/ 7 | /en/* /:splat 8 | 9 | /zh-cn/essentials/getting-started.html /zh/guide/ 10 | /zh-cn/essentials/* /zh/guide/essentials/:splat 11 | /zh-cn/advanced/* /zh/guide/advanced/:splat 12 | /zh-cn/api/* /zh/api/ 13 | /zh-cn/* /zh/:splat 14 | 15 | /ru/essentials/getting-started.html /ru/guide/ 16 | /ru/essentials/* /ru/guide/essentials/:splat 17 | /ru/advanced/* /ru/guide/advanced/:splat 18 | /ru/api/* /ru/api/ 19 | /ru/* /ru/:splat 20 | 21 | /ja/essentials/getting-started.html /ja/guide/ 22 | /ja/essentials/* /ja/guide/essentials/:splat 23 | /ja/advanced/* /ja/guide/advanced/:splat 24 | /ja/api/* /ja/api/ 25 | /ja/* /ja/:splat 26 | 27 | /kr/essentials/getting-started.html /kr/guide/ 28 | /kr/essentials/* /kr/guide/essentials/:splat 29 | /kr/advanced/* /kr/guide/advanced/:splat 30 | /kr/api/* /kr/api/ 31 | /kr/* /kr/:splat 32 | -------------------------------------------------------------------------------- /docs/.vuepress/public/bit-wide.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/bit-wide.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/android-chrome-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/android-chrome-192x192.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/android-chrome-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/android-chrome-512x512.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon-120x120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon-120x120.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon-152x152.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon-180x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon-180x180.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon-60x60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon-60x60.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon-76x76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon-76x76.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/apple-touch-icon.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/favicon-16x16.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/favicon-32x32.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/msapplication-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/msapplication-icon-144x144.png -------------------------------------------------------------------------------- /docs/.vuepress/public/icons/mstile-150x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/icons/mstile-150x150.png -------------------------------------------------------------------------------- /docs/.vuepress/public/images/vueschool/vs-close.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /docs/.vuepress/public/images/vueschool/vs-iso.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/.vuepress/public/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/logo.png -------------------------------------------------------------------------------- /docs/.vuepress/public/sponsors/passionate-people-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/sponsors/passionate-people-dark.png -------------------------------------------------------------------------------- /docs/.vuepress/public/sponsors/passionate-people-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/sponsors/passionate-people-light.png -------------------------------------------------------------------------------- /docs/.vuepress/public/sponsors/vuejobs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vuejs/vue-router/786ed347ef0e72adc8a3ebe86d5105dd8748c0a6/docs/.vuepress/public/sponsors/vuejobs.png -------------------------------------------------------------------------------- /docs/.vuepress/styles/index.styl: -------------------------------------------------------------------------------- 1 | .bit-sponsor 2 | font-weight 600 3 | background-color #f3f6f8 4 | padding 0.6em 1.2em 5 | border-radius 8px 6 | display inline-block 7 | margin 1em 0 !important 8 | a 9 | color #999 10 | img 11 | height 40px 12 | margin-left 15px 13 | img, span 14 | vertical-align middle 15 | 16 | 17 | .vueschool 18 | background-color #e7ecf3 19 | padding 1em 1.25em 20 | border-radius 2px 21 | color #486491 22 | position relative 23 | display flex 24 | a 25 | color #486491 !important 26 | position relative 27 | padding-left 36px 28 | &:before 29 | content '' 30 | position absolute 31 | display block 32 | width 30px 33 | height 30px 34 | top calc(50% - 15px); 35 | left -4px 36 | border-radius 50% 37 | background-color #73abfe 38 | &:after 39 | content '' 40 | position absolute 41 | display block 42 | width 0 43 | height 0 44 | top calc(50% - 5px) 45 | left 8px 46 | border-top 5px solid transparent 47 | border-bottom 5px solid transparent 48 | border-left 8px solid #fff 49 | 50 | @media (max-width: 719px) { 51 | .vueschool { 52 | display: inline-flex; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /docs/.vuepress/theme/components/CarbonAds.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 27 | 28 | 85 | -------------------------------------------------------------------------------- /docs/.vuepress/theme/index.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extend: '@vuepress/theme-default' 3 | } 4 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Get Started → 5 | actionLink: /installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | Vue Router is the official router for [Vue.js](http://vuejs.org). It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include: 10 | 11 | - Nested route/view mapping 12 | - Modular, component-based router configuration 13 | - Route params, query, wildcards 14 | - View transition effects powered by Vue.js' transition system 15 | - Fine-grained navigation control 16 | - Links with automatic active CSS classes 17 | - HTML5 history mode or hash mode, with auto-fallback in IE9 18 | - Customizable Scroll Behavior 19 | 20 | [Get started](./guide/) or play with the [examples](https://github.com/vuejs/vue-router/tree/dev/examples) (see [`README.md`](https://github.com/vuejs/vue-router/) to run them). 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/fr/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Get Started → 5 | actionLink: /fr/installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | Vue Router est le router officiel pour [Vue.js](http://vuejs.org). Il s'intègre aisément avec Vue.js pour faire des applications mono page avec Vue.js. Fonctionnalités incluses: 10 | 11 | - Vues et routes imbriquées 12 | - Modulaire, configuration basée sur les composants 13 | - Paramètres de route, de requête 14 | - Effets de transition de vues basées sur le systeme de transition de Vue.js 15 | - Gestion fine de la navigation 16 | - Classes CSS pour liens actifs 17 | - Mode HTML5 de la gestion de l'historique ou mode par hash, avec solution de repli automatique pour IE9 18 | - Gestion du scroll 19 | 20 | [Pour commencer](./guide/) ou jouer avec les [exemples](https://github.com/vuejs/vue-router/tree/dev/examples) (voir [`README.md`](https://github.com/vuejs/vue-router/) pour les faire fonctionner). 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/fr/guide/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # Champs meta de route 2 | 3 | Vous pouvez inclure un champ `meta` quand vous définissez une route : 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // un champ `meta` 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | Comment maintenant accéder à ce champ `meta` ? 25 | 26 | Tout d'abord, chaque objet route dans la configuration de `routes` est appelé un **registre de route**. Les registres de route peuvent être imbriqués. Par conséquent, quand une route concorde, elle peut potentiellement concorder avec plus d'un registre de route. 27 | 28 | Par exemple, avec la configuration de route ci-dessous, l'URL `/foo/bar` va concorder avec le registre parent et le registre enfant. 29 | 30 | Tous les registres concordants avec une route sont exposés dans l'objet `$route` (ainsi que les objets de route dans les sécurisations de navigation) dans le tableau `$route.matched`. Donc, nous devons itérer à travers `$route.matched` pour vérifier les champs meta dans les registres de route. 31 | 32 | Un exemple concret est la vérification d'un champ meta dans une interception de navigation globale : 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // cette route demande une autorisation, vérifions si l'utilisateur est logué. 38 | // sinon, redirigeons le sur la page de login. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // assurez vous de toujours appeler `next()` ! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs/fr/guide/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # Transitions 2 | 3 | Vu que `` est essentiellement un composant dynamique, on peut lui appliquer certains effets de transitions en utilisant le composant `` : 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [Tout à propos de ``](https://fr.vuejs.org/v2/guide/transitions.html) fonctionne également ici de la même manière. 12 | 13 | ## Transition par route 14 | 15 | L'utilisation du dessus applique la même transition pour chaque route. Si vous voulez que les composants de route aient des transitions différentes, vous pouvez utiliser à la place `` avec des noms différents à l'intérieur de chaque composant de route : 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | ## Transition dynamique basée sur la route 36 | 37 | Il est aussi possible de déterminer la transition à utiliser en se basant sur la relation entre la route cible et la route actuelle : 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // et dans le composant parent, 48 | // observer la `$route` pour déterminer la transition à utiliser 49 | watch: { 50 | '$route' (to, from) { 51 | const toDepth = to.path.split('/').length 52 | const fromDepth = from.path.split('/').length 53 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 54 | } 55 | } 56 | ``` 57 | 58 | Voir un exemple complet [ici](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). 59 | -------------------------------------------------------------------------------- /docs/fr/guide/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Routes nommées 2 | 3 | Parfois il est plus pratique d'identifier une route avec un nom, tout particulièrement quand on souhaite attacher cette route ou exécuter des actions de navigation. Vous pouvez donner un nom à une route dans les options `routes` pendant la création de l'instance du routeur : 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/utilisateur/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Pour attacher une route nommée, vous pouvez passer un objet à la prop `to` du composant `router-link` : 18 | 19 | ``` html 20 | Utilisateur 21 | ``` 22 | 23 | C'est exactement le même objet à utiliser programmatiquement avec `router.push()` : 24 | 25 | ``` js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | Dans les deux cas, le routeur va naviguer vers le chemin `/utilisateur/123`. 30 | 31 | Un exemple complet se trouve [ici](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 32 | -------------------------------------------------------------------------------- /docs/fr/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | ## Téléchargement direct / CDN 4 | 5 | [https://unpkg.com/vue-router@3/dist/vue-router.js](https://unpkg.com/vue-router@3/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) fournit des liens CDN basés sur npm. Le lien ci-dessus pointera toujours vers la dernière version sur npm. Vous pouvez aussi utiliser un tag ou une version spécifique via un URL comme `https://unpkg.com/vue-router@3.0.0/dist/vue-router.js`. 9 | 10 | 11 | Incluez `vue-router` après Vue et l'installation sera automatique : 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ## npm 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | Lorsqu'il est utilisé avec un système de module, vous devez explicitement installer le router via `Vue.use()` : 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | Vous n'avez pas besoin de faire cela lors de l'utilisation des balises de script globales (` 15 | 16 | ``` 17 | 18 | ## npm 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | When used with a module system, you must explicitly install the router via `Vue.use()`: 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | You don't need to do this when using global script tags. 34 | 35 | ## Vue CLI 36 | 37 | If you have a project using [Vue CLI](https://cli.vuejs.org/) you can add Vue Router as a plugin. You can let the CLI generate the code above for you as well as two sample routes. **It will also overwrite your `App.vue`** so make sure to backup the file before running the following command inside your project: 38 | 39 | ```sh 40 | vue add router 41 | ``` 42 | 43 | ## Dev Build 44 | 45 | You will have to clone directly from GitHub and build `vue-router` yourself if 46 | you want to use the latest dev build. 47 | 48 | ``` bash 49 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 50 | cd node_modules/vue-router 51 | npm install 52 | npm run build 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /docs/ja/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Get Started → 5 | actionLink: /ja/installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | 10 | 11 | Vue Router は [Vue.js](http://vuejs.org) 公式ルータです。これは Vue.js のコアと深く深く統合されており、Vue.js でシングルページアプリケーションを構築します。機能は次の通りです: 12 | 13 | - ネストされたルート/ビューマッピング 14 | - モジュール式、コンポーネントベースのルータ構造 15 | - ルートパラメータ、クエリ、ワイルドカード 16 | - Vue.js の transition 機能による、transition エフェクトの表示 17 | - 細かいナビゲーションコントロール 18 | - 自動で付与される active CSS クラス 19 | - HTML5 history モードまたは hash モードと IE9 の互換性 20 | - カスタマイズ可能なスクロール動作 21 | 22 | [はじめに](./guide/) または [例](https://github.com/vuejs/vue-router/tree/dev/examples) から試してください。 ([`README.md`](https://github.com/vuejs/vue-router/)を参照してください。). 23 | 24 | 25 | -------------------------------------------------------------------------------- /docs/ja/guide/advanced/lazy-loading.md: -------------------------------------------------------------------------------- 1 | # 遅延ローディングルート 2 | 3 | 4 | 5 | バンドラーを使ってアプリケーションを構築している時、バンドルされる JavaScript が非常に大きいものになり得ます。結果的にページのロード時間に影響を与えてしまいます。もし各ルートコンポーネントごとに別々のチャンクにして、訪れたルートの時だけロードできればより効率的でしょう。 6 | 7 | Vue の [非同期コンポーネント機能](http://jp.vuejs.org/guide/components.html#非同期コンポーネント) と webpack の [コード分割機能](https://webpack.js.org/guides/code-splitting-async/) を組み合わせることでとても簡単に遅延ロードするルートコンポーネントができます。 8 | 9 | 最初に、非同期コンポーネントは Promise (コンポーネント自身解決する必要がある) を返すファクトリ関数として定義できます: 10 | 11 | ```js 12 | const Foo = () => 13 | Promise.resolve({ 14 | /* component definition */ 15 | }) 16 | ``` 17 | 18 | 次に、webpack 2 において [動的 import](https://github.com/tc39/proposal-dynamic-import) 構文を使用して、コード分割ポイントを示すことができます: 19 | 20 | ```js 21 | import('./Foo.vue') // returns a Promise 22 | ``` 23 | 24 | > Note: Babel を使用している場合、Babel が構文を正しく解析するために [syntax-dynamic-import](https://babeljs.io/docs/plugins/syntax-dynamic-import/) プラグインを追加する必要があります。 25 | 26 | 2 つを組み合わせることで、これは、webpack によって自動的にコード分割される非同期コンポーネントを定義する方法です: 27 | 28 | ```js 29 | const Foo = () => import('./Foo.vue') 30 | ``` 31 | 32 | ## 同じチャンク内でのコンポーネントグループ化 33 | 34 | しばしば同じ非同期のチャンクに、そのルート配下のネストされた全てのコンポーネントをグループ化したいと思うかもしれません。それを実現するためには、 特別なコメント構文 (webpack > 2.4 必須)を使用してチャンクの名前を提供する [名前付きチャンク](https://webpack.js.org/api/module-methods/#magic-comments) を使う必要があります。 35 | 36 | ```js 37 | const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') 38 | const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') 39 | const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') 40 | ``` 41 | 42 | webpack は同じチャンク名のどんな非同期のモジュールも同じ非同期のチャンクにグループします。 43 | -------------------------------------------------------------------------------- /docs/ja/guide/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # ルートメタフィールド 2 | 3 | 4 | 5 | ルートの定義をする際に `meta` フィールドを含めることができます。 6 | 7 | ```js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { 11 | path: '/foo', 12 | component: Foo, 13 | children: [ 14 | { 15 | path: 'bar', 16 | component: Bar, 17 | // メタフィールド 18 | meta: { requiresAuth: true } 19 | } 20 | ] 21 | } 22 | ] 23 | }) 24 | ``` 25 | 26 | ではどのように `meta` フィールドにアクセスしましょう? 27 | 28 | まず、 `routes` 設定の中の各ルートオブジェクトは**ルートレコード**と呼ばれます。ルートレコードはネストされているかもしれません。したがって、ルートがマッチした時に、潜在的には 1 つ以上のルートレコードがマッチされる可能性があります。 29 | 30 | 例えば上記のルート設定で、 `/foo/bar` という URL は親のルートレコードにも子のルートレコードにもマッチします。 31 | 32 | ルートにマッチした全てのルートレコードは `$route.matched` 配列として `$route` オブジェクト上で (また、ナビゲーションガード上のルートオブジェクトでも) アクセス可能になります。 33 | 34 | メタフィールドをグローバルナビゲーションガードで確認するユースケースの例: 35 | 36 | ```js 37 | router.beforeEach((to, from, next) => { 38 | if (to.matched.some(record => record.meta.requiresAuth)) { 39 | // このルートはログインされているかどうか認証が必要です。 40 | // もしされていないならば、ログインページにリダイレクトします。 41 | if (!auth.loggedIn()) { 42 | next({ 43 | path: '/login', 44 | query: { redirect: to.fullPath } 45 | }) 46 | } else { 47 | next() 48 | } 49 | } else { 50 | next() // next() を常に呼び出すようにしてください! 51 | } 52 | }) 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/ja/guide/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # トランジション 2 | 3 | 4 | 5 | 基本的に `` は動的コンポーネントなので、 `` コンポーネントを使うのと同じ方法でトランジションを適用することができます。 6 | 7 | ```html 8 | 9 | 10 | 11 | ``` 12 | 13 | [全てのトランジション API は](http://jp.vuejs.org/guide/transitions.html) はここでも動作します。 14 | 15 | ## ルート単位のトランジション 16 | 17 | 上記の使い方では全てのトランジションが全てのルートに対して適用されます。もし各ルートコンポーネントにそれぞれ違うトランジションを持たせたい場合は、代わりにルーターコンポーネント内で異なる名前で `` を使うことができます。 18 | 19 | ```js 20 | const Foo = { 21 | template: ` 22 | 23 |
...
24 |
25 | ` 26 | } 27 | 28 | const Bar = { 29 | template: ` 30 | 31 |
...
32 |
33 | ` 34 | } 35 | ``` 36 | 37 | ## ルートベースの動的トランジション 38 | 39 | 対象のルートと現在のルートの関係を元に動的にトランジションを決定することも可能です。 40 | 41 | ```html 42 | 43 | 44 | 45 | 46 | ``` 47 | 48 | ```js 49 | // そして親コンポーネントの中で、 50 | // `$route` を watch して使用するトランジションを決定します 51 | watch: { 52 | '$route' (to, from) { 53 | const toDepth = to.path.split('/').length 54 | const fromDepth = from.path.split('/').length 55 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 56 | } 57 | } 58 | ``` 59 | 60 | 完全な例は [こちら](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js) をご参照ください。 61 | -------------------------------------------------------------------------------- /docs/ja/guide/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # 名前付きルート 2 | 3 | 4 | 5 | しばしば、名前を使ってルートを特定できるとより便利です。特にルートにリンクするときやナビゲーションを実行するときなどです。Router インスタンスを作成するときに `routes` オプションの中でルートに名前を付けることができます。 6 | 7 | ```js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { 11 | path: '/user/:userId', 12 | name: 'user', 13 | component: User 14 | } 15 | ] 16 | }) 17 | ``` 18 | 19 | 名前を付けたルートにリンクするには、 `router-link` コンポーネントの `to` プロパティにオブジェクトを渡します。 20 | 21 | ```html 22 | User 23 | ``` 24 | 25 | これはプログラムで `router.push()` を呼び出すときに使われるオブジェクトと全く同じです。 26 | 27 | ```js 28 | router.push({ name: 'user', params: { userId: 123 } }) 29 | ``` 30 | 31 | どちらのケースもルーターは `/user/123` のパスにナビゲーションします。 32 | 33 | 完全な例は [こちら](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js) です。 34 | -------------------------------------------------------------------------------- /docs/ja/guide/essentials/redirect-and-alias.md: -------------------------------------------------------------------------------- 1 | # リダイレクトとエイリアス 2 | 3 | 4 | 5 | ### リダイレクト 6 | 7 | `routes` 設定でリダイレクトが可能です。`/a` から `/b` へリダイレクトする例: 8 | 9 | ```js 10 | const router = new VueRouter({ 11 | routes: [{ path: '/a', redirect: '/b' }] 12 | }) 13 | ``` 14 | 15 | 名前付きルートに対してリダイレクトすることもできます。 16 | 17 | ```js 18 | const router = new VueRouter({ 19 | routes: [{ path: '/a', redirect: { name: 'foo' } }] 20 | }) 21 | ``` 22 | 23 | また、function を使った動的なリダイレクトもできます。 24 | 25 | ```js 26 | const router = new VueRouter({ 27 | routes: [ 28 | { 29 | path: '/a', 30 | redirect: to => { 31 | // この function は対象のルートを引数として受け取ります 32 | // ここではリダイレクト先の path もしくは location を返します 33 | } 34 | } 35 | ] 36 | }) 37 | ``` 38 | 39 | [ナビゲーションガード](../advanced/navigation-guards.md)はリダイレクトするルートに提供されず、ターゲット上のみに適用されるということに注意してください。例では、`beforeEnter` ガードを `/a` ルートに追加しても効果がありません。 40 | 41 | その他の高度な使い方として、[例](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js) をご参照ください。 42 | 43 | ### エイリアス 44 | 45 | リダイレクトが意図するところは、ユーザーが `/a` に訪問した時に URL を `/b` に置換し、そして `/b` にマッチさせます。ではエイリアスは何でしょうか? 46 | 47 | **`/b` として扱う `/a` のエイリアスは、ユーザーが `/b` に訪問した時に URL は `/b` のままになります。しかし、それはまるでユーザーが `/a` に訪問したかのようにマッチされます。** 48 | 49 | 上記はルートの設定で以下のように表現されます。 50 | 51 | ```js 52 | const router = new VueRouter({ 53 | routes: [{ path: '/a', component: A, alias: '/b' }] 54 | }) 55 | ``` 56 | 57 | 設定のネスト構造による制約とは異なり、エイリアスは UI 構造に任意の URL をマップするための自由さがあります。 58 | 59 | 高度な使い方に関しては、 [例](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js) をご参照ください。 60 | -------------------------------------------------------------------------------- /docs/ja/installation.md: -------------------------------------------------------------------------------- 1 | # インストール 2 | 3 | ### 直接ダウンロード / CDN 4 | 5 | [https://unpkg.com/vue-router@3/dist/vue-router.js](https://unpkg.com/vue-router@3/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) は npm ベースの CDN リンクです。 上記のリンクは常に NPM 上の最新のリリースを指します。 `https://unpkg.com/vue-router@3.0.0/dist/vue-router.js` のような URL を利用することで特定のバージョンやタグを指定することもできます。 9 | 10 | 11 | Vue の後に `vue-router` を含めると自動的にインストールされます。 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### npm 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | モジュールシステムを使う場合、`Vue.use()` を使って明示的にルーターをインストールする必要があります。 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | グローバルな script タグを使っている場合は必要ありません。 34 | 35 | ## Vue CLI 36 | 37 | [Vue CLI](https://cli.vuejs.org/) を使用している場合、 Vue Router をプラグインで追加することができます。2つのサンプルルートと同様、上記のコードを CLI に生成させることができます。**`App.vue`もまた上書きされるため、** プロジェクト内で以下のコマンドを実行する前にファイルをバックアップしておいてください: 38 | 39 | ```sh 40 | vue add router 41 | ``` 42 | 43 | ### 開発用ビルド 44 | 45 | もし最新の開発用ビルドを使用したい場合は、GitHub から直接クローンして `vue-router` をご自身でビルドしてください。 46 | 47 | ``` bash 48 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 49 | cd node_modules/vue-router 50 | npm install 51 | npm run build 52 | ``` 53 | -------------------------------------------------------------------------------- /docs/kr/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Get Started → 5 | actionLink: /kr/installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | Vue 라우터는 [Vue.js](http://vuejs.org)의 공식 라우터입니다. 10 | Vue.js를 사용한 싱글 페이지 앱을 쉽게 만들 수 있도록 Vue.js의 코어와 긴밀히 통합되어 있습니다. 11 | 12 | 아래의 기능을 포함합니다. 13 | 14 | - 중첩된 라우트/뷰 매핑 15 | - 모듈화된, 컴포넌트 기반의 라우터 설정 16 | - 라우터 파라미터, 쿼리, 와일드카드 17 | - Vue.js의 트랜지션 시스템을 이용한 트랜지션 효과 18 | - 세밀한 네비게이션 컨트롤 19 | - active CSS 클래스를 자동으로 추가해주는 링크 20 | - HTML5 히스토리 모드 또는 해시 모드(IE9에서 자동으로 폴백) 21 | - 사용자 정의 가능한 스크롤 동작 22 | 23 | [시작하기](./guide/) 또는 [예제](https://github.com/vuejs/vue-router/tree/dev/examples)를 참고하세요. ([`README.md`](https://github.com/vuejs/vue-router/)에서 사용법을 확인할 수 있습니다). 24 | 25 | 26 | -------------------------------------------------------------------------------- /docs/kr/guide/advanced/lazy-loading.md: -------------------------------------------------------------------------------- 1 | # 지연된 로딩 2 | 3 | 번들러를 이용하여 앱을 제작할 때 JavaScript 번들이 상당히 커져 페이지로드 시간에 영향을 줄 수 있습니다. 각 라우트의 컴포넌트를 별도의 단위로 분할하고 경로를 방문할 때 로드하는 것이 효율적일 것입니다. 4 | 5 | Vue의 [비동기 컴포넌트](http://vuejs.org/guide/components.html#Async-Components)와 Webpack의 [코드 분할](https://webpack.js.org/guides/code-splitting-async/)을 결합합니다. 라우트 컴포넌트를 쉽게 불러올 수 있습니다. 6 | 7 | 첫째, 비동기 컴포넌트는 Promise를 반환하는 팩토리 함수로 정의할 수 있습니다 (컴포넌트가 resolve 되어야함). 8 | 9 | ```js 10 | const Foo = () => 11 | Promise.resolve({ 12 | /* 컴포넌트 정의 */ 13 | }) 14 | ``` 15 | 16 | 둘째, Webpack 2에서 [dynamic import](https://github.com/tc39/proposal-dynamic-import)를 사용하여 코드 분할 포인트를 지정할 수 있습니다. 17 | 18 | ```js 19 | import('./Foo.vue') // returns a Promise 20 | ``` 21 | 22 | > 참고: Babel을 사용하고 있는 경우 올바른 구문 분석을 위해 [syntax-dynamic-import](http://babeljs.io/docs/plugins/syntax-dynamic-import/) 플러그인을 추가해야합니다. 23 | 24 | 이 두 가지를 결합하여 Webpack에 의해 자동으로 코드 분할될 비동기 컴포넌트를 정의하는 방법입니다. 25 | 26 | ```js 27 | const Foo = () => import('./Foo.vue') 28 | ``` 29 | 30 | 라우트 설정에서 아무것도 바꿀 필요가 없습니다. `Foo`만 사용하면 됩니다. 31 | 32 | ```js 33 | const router = new VueRouter({ 34 | routes: [{ path: '/foo', component: Foo }] 35 | }) 36 | ``` 37 | 38 | ### 같은 묶음으로 컴포넌트 그룹화하기 39 | 40 | 때로는 동일한 라우트 아래에 중첩된 모든 컴포넌트를 동일한 비동기 묶음으로 그룹화 할 수 있습니다. 이를 위해 특수 주석 문법을 사용하는 이름(Webpack 2.4 이상 지원)을 제공하여 [이름을 가진 묶음](https://webpack.js.org/api/module-methods/#magic-comments)을 사용해야합니다. 41 | 42 | ```js 43 | const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') 44 | const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') 45 | const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') 46 | ``` 47 | 48 | Webpack은 동일한 이름의 묶음을 가진 비동기 모듈을 동일한 비동기 묶음으로 그룹화합니다. 49 | -------------------------------------------------------------------------------- /docs/kr/guide/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # 라우트 메타 필드 2 | 3 | 라우트를 정의 할 때 `meta` 필드를 포함시킬 수 있습니다. 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // 메타 필드 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | 그렇다면 이 `메타`필드에 어떻게 접근할까요? 25 | 26 | 첫째,`routes` 설정의 각 라우트 객체를 **라우트 레코드** 라고합니다. 라우트 레코드는 중첩 될 수 있습니다. 따라서 라우트가 일치하면 둘 이상의 라우트 레코드와 잠재적으로 일치 할 수 있습니다. 27 | 28 | 예를 들어, 위의 라우트 구성에서 URL `/foo/bar`는 상위 라우트 레코드와 하위 라우트 레코드 모두와 일치합니다. 29 | 30 | 라우트와 일치하는 모든 라우트 레코드는 `$route` 객체(그리고 네비게이션 가드의 라우트 객체)에 `$route.matched` 배열로 노출됩니다. 그러므로 우리는 `$route.matched`를 반복하여 라우트 레코드의 메타 필드를 검사 할 필요가 있습니다. 31 | 32 | 예제 사용 사례는 글로벌 네비게이션 가드에서 메타 필드를 확인하는 것입니다. 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // 이 라우트는 인증이 필요하며 로그인 한 경우 확인하십시오. 38 | // 그렇지 않은 경우 로그인 페이지로 리디렉션하십시오. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // 반드시 next()를 호출하십시오! 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs/kr/guide/advanced/scroll-behavior.md: -------------------------------------------------------------------------------- 1 | # 스크롤 동작 2 | 3 | 클라이언트 측 라우팅을 사용할 때 새로운 경로로 이동할 때 맨 위로 스크롤하거나 실제 페이지를 다시 로드하는 것처럼 컨텐츠 항목의 스크롤 위치를 유지할 수 있습니다. `vue-router`는 이러한 것들을 할 수 있으며, 라우트 탐색에서 스크롤 동작을 완전히 사용자 정의할 수 있게합니다. 4 | 5 | **참고: 이 기능은 HTML5 히스토리 모드에서만 작동합니다.** 6 | 7 | 라우터 인스턴스를 생성 할 때 `scrollBehavior` 함수를 제공 할 수 있습니다. 8 | 9 | ``` js 10 | const router = new VueRouter({ 11 | routes: [...], 12 | scrollBehavior (to, from, savedPosition) { 13 | // 원하는 위치로 돌아가기 14 | } 15 | }) 16 | ``` 17 | 18 | `scrollBehavior` 함수는 `to`와 `from` 라우트 객체를받습니다. 세 번째 전달인자인 `savedPosition`은 브라우저의 뒤로/앞으로 버튼으로 트리거되는 `popstate` 네비게이션인 경우에만 사용할 수 있습니다. 19 | 20 | 이 함수는 스크롤 위치 객체를 반환 할 수 있습니다. 객체는 다음과 같은 형태 일 수 있습니다. 21 | 22 | - `{ x: number, y: number }` 23 | - `{ selector: string, offset? : { x: number, y: number }}` (offset은 2.6.0 이상만 지원) 24 | 25 | 잘못된 값이나 빈 객체가 반환되면 스크롤이 발생하지 않습니다. 26 | 27 | 예제: 28 | 29 | ``` js 30 | scrollBehavior (to, from, savedPosition) { 31 | return { x: 0, y: 0 } 32 | } 33 | ``` 34 | 35 | 그러면 모든 라우트 네비게이션에 대해 페이지가 맨 위로 스크롤됩니다. 36 | 37 | `savedPosition`을 반환하면 뒤로/앞으로 버튼으로 탐색할 때 네이티브와 같은 동작이 발생합니다. 38 | 39 | ``` js 40 | scrollBehavior (to, from, savedPosition) { 41 | if (savedPosition) { 42 | return savedPosition 43 | } else { 44 | return { x: 0, y: 0 } 45 | } 46 | } 47 | ``` 48 | 49 | "anchor로 스크롤" 동작을 시뮬레이트하려면 다음을 수행하십시오. 50 | 51 | ``` js 52 | scrollBehavior (to, from, savedPosition) { 53 | if (to.hash) { 54 | return { 55 | selector: to.hash 56 | // , offset: { x: 0, y: 10 } 57 | } 58 | } 59 | } 60 | ``` 61 | 62 | 또한 [라우트 메타 필드](meta.md)를 사용하여 세밀한 스크롤 동작 제어를 구현할 수 있습니다. 전체 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js)를 확인하십시오. 63 | -------------------------------------------------------------------------------- /docs/kr/guide/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # 트랜지션 2 | 3 | ``는 본질적으로 동적인 컴포넌트이기 때문에 `` 컴포넌트를 사용하는 것과 같은 방식으로 트랜지션 효과를 적용할 수 있습니다. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | [``에 대한 모든 것](http://vuejs.org/guide/transitions.html) 을 확인하십시오. 12 | 13 | ### 라우트 별 트랜지션 14 | 15 | 위의 사용법은 모든 라우트에 대해 동일한 트랜지션을 적용합니다. 각 라우트의 컴포넌트가 서로 다른 트랜지션을 갖도록 하려면 각 라우트 컴포넌트 내에서 다른 이름으로 ``을 사용할 수 있습니다. 16 | 17 | ``` js 18 | const Foo = { 19 | template: ` 20 | 21 |
...
22 |
23 | ` 24 | } 25 | 26 | const Bar = { 27 | template: ` 28 | 29 |
...
30 |
31 | ` 32 | } 33 | ``` 34 | 35 | ### 라우트 기반 동적 트랜지션 36 | 37 | 또한 대상 라우트와 현재 라우트 간의 관계를 기반으로 동적으로 사용할 트랜지션을 결정할 수도 있습니다. 38 | 39 | ``` html 40 | 41 | 42 | 43 | 44 | ``` 45 | 46 | ``` js 47 | // 그런 다음 부모 구성 요소에서 `$route`를 보고 사용할 트랜지션을 결정합니다 48 | watch: { 49 | '$route' (to, from) { 50 | const toDepth = to.path.split('/').length 51 | const fromDepth = from.path.split('/').length 52 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 53 | } 54 | } 55 | ``` 56 | 57 | 전체 예제는 [여기](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js)에 있습니다. 58 | -------------------------------------------------------------------------------- /docs/kr/guide/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # 이름을 가지는 라우트 2 | 3 | 때로는 라우트에 연결하거나 탐색을 수행 할 때 이름이 있는 라우트를 사용하는 것이 더 편리합니다. Router 인스턴스를 생성하는 동안 `routes` 옵션에 라우트를 지정할 수 있습니다. 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | 이름을 가진 라우트에 링크하려면, 객체를 `router-link`, 컴포넌트의 `to` prop로 전달할 수 있습니다. 18 | 19 | ``` html 20 | User 21 | ``` 22 | 23 | 이것은 `router.push()`와 프로그램적으로 사용되는 것과 정확히 같은 객체입니다. 24 | 25 | ```js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | 두 경우 모두 라우터는 `/user/123` 경로로 이동합니다. 30 | 31 | 전체 예제는 [여기](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js)에 있습니다. 32 | -------------------------------------------------------------------------------- /docs/kr/guide/essentials/named-views.md: -------------------------------------------------------------------------------- 1 | # 이름을 가지는 뷰 2 | 3 | 때로는 여러 개의 뷰를 중첩하지 않고 동시에 표시해야 하는 경우가 있습니다. `sidebar` 뷰와 `main` 뷰로 레이아웃을 생성합니다. 이름이 지정된 뷰가 편리한 경우 입니다. 뷰에 하나의 outlet이 있는 대신 여러 개를 사용하여 각 outlet에 이름을 지정할 수 있습니다. 이름이 없는 `router-view`는 이름으로 `default`가 주어집니다. 4 | 5 | ``` html 6 | 7 | 8 | 9 | ``` 10 | 11 | 뷰는 컴포넌트를 사용하여 렌더링 되므로 여러 뷰에는 동일한 라우트에 대해 여러 컴포넌트가 필요합니다. `components`(s를 붙입니다) 옵션을 사용해야합니다. 12 | 13 | ``` js 14 | const router = new VueRouter({ 15 | routes: [ 16 | { 17 | path: '/', 18 | components: { 19 | default: Foo, 20 | a: Bar, 21 | b: Baz 22 | } 23 | } 24 | ] 25 | }) 26 | ``` 27 | 28 | 이 예제는 [여기](https://jsfiddle.net/posva/6du90epg/)에서 확인할 수 있습니다. 29 | -------------------------------------------------------------------------------- /docs/kr/guide/essentials/passing-props.md: -------------------------------------------------------------------------------- 1 | # 라우트 컴포넌트에 속성 전달 2 | 3 | 컴포넌트에서 `$route`를 사용하면 특정 URL에서만 사용할 수 있는 컴포넌트의 유연성을 제한하는 라우트와 강한 결합을 만듭니다. 4 | 5 | 컴포넌트와 라우터 속성을 분리하려면 다음과 같이 하십시오. 6 | 7 | **$route에 의존성 추가** 8 | 9 | ``` js 10 | const User = { 11 | template: '
User {{ $route.params.id }}
' 12 | } 13 | const router = new VueRouter({ 14 | routes: [ 15 | { path: '/user/:id', component: User } 16 | ] 17 | }) 18 | ``` 19 | 20 | **속성에 의존성 해제** 21 | 22 | ``` js 23 | const User = { 24 | props: ['id'], 25 | template: '
User {{ id }}
' 26 | } 27 | const router = new VueRouter({ 28 | routes: [ 29 | { path: '/user/:id', component: User, props: true }, 30 | ] 31 | }) 32 | ``` 33 | 34 | 이를 통해 어디서나 컴포넌트를 사용할 수 있으므로 컴포넌트 재사용 및 테스트하기가 더 쉽습니다. 35 | 36 | ### Boolean 모드 37 | 38 | `props`를 `true`로 설정하면 `route.params`가 컴포넌트 `props`로 설정됩니다. 39 | 40 | ### 객체 모드 41 | 42 | `props`가 객체일때 컴포넌트 `props`가 있는 그대로 설정됩니다. 43 | `props`가 정적일 때 유용합니다. 44 | 45 | ``` js 46 | const router = new VueRouter({ 47 | routes: [ 48 | { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } } 49 | ] 50 | }) 51 | ``` 52 | 53 | ### 함수 모드 54 | 55 | `props`를 반환하는 함수를 만들 수 있습니다. 이를 통해 전달인자를 다른 타입으로 캐스팅하고 적정인 값을 라우트 기반 값과 결합됩니다. 56 | 57 | ``` js 58 | const router = new VueRouter({ 59 | routes: [ 60 | { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) } 61 | ] 62 | }) 63 | ``` 64 | 65 | `/search?q=vue`는 `{query: "vue"}`를 `SearchUser` 컴포넌트에 전달합니다. 66 | 67 | 라우트 변경시에만 평가되므로 `props` 함수는 상태를 저장하지 않도록 합니다. 68 | `props`를 정의할 상태가 필요한 경우 래퍼 컴포넌트를 사용하면 상태가 변경될 때마다 응답할 수 있습니다. 69 | 70 | 고급 사용예를 보려면 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js)를 확인하세요. 71 | -------------------------------------------------------------------------------- /docs/kr/guide/essentials/redirect-and-alias.md: -------------------------------------------------------------------------------- 1 | # 리다이렉트와 별칭 2 | 3 | ### 리다이렉트 4 | 5 | 리디렉션은 `routes` 설정에서도 할 수 있습니다. `/a`에서 `/b`로 리디렉션하려면 6 | 7 | ``` js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { path: '/a', redirect: '/b' } 11 | ] 12 | }) 13 | ``` 14 | 15 | 리디렉션은 이름이 지정된 라우트를 지정할 수도 있습니다. 16 | 17 | ``` js 18 | const router = new VueRouter({ 19 | routes: [ 20 | { path: '/a', redirect: { name: 'foo' }} 21 | ] 22 | }) 23 | ``` 24 | 25 | 또는 동적 리디렉션을 위한 함수를 사용할 수도 있습니다. 26 | 27 | ``` js 28 | const router = new VueRouter({ 29 | routes: [ 30 | { path: '/a', redirect: to => { 31 | // 함수는 인수로 대상 라우트를 받습니다. 32 | // 여기서 path/location 반환합니다. 33 | }} 34 | ] 35 | }) 36 | ``` 37 | 기타 고급 사용법은 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js)를 확인 하십시오. 38 | 39 | ### 별칭 40 | 41 | 리다이렉트는 사용자가 `/a`를 방문했을 때 URL이 `/b`로 대체 된 다음 `/b`로 매칭된다는 것을 의미합니다. 하지만 별칭이란 무엇입니까? 42 | 43 | **`/a`의 별칭은 `/b`는 사용자가 `/b`를 방문했을 때 URL은 `/b`을 유지하지만 사용자가 `/a`를 방문한 것처럼 매칭합니다.** 44 | 45 | 위는 라우트 구성에서 다음과 같이 표현할 수 있습니다. 46 | 47 | ``` js 48 | const router = new VueRouter({ 49 | routes: [ 50 | { path: '/a', component: A, alias: '/b' } 51 | ] 52 | }) 53 | ``` 54 | 55 | 별칭을 사용하면 구성의 중첩 구조에 의해 제약을 받는 대신 UI 구조를 임의의 URL에 매핑 할 수 있습니다. 56 | 57 | 기타 고급 사용법은 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js)를 확인 하십시오. 58 | -------------------------------------------------------------------------------- /docs/kr/installation.md: -------------------------------------------------------------------------------- 1 | # 설치 2 | 3 | ### 직접 다운로드 / CDN 4 | 5 | [https://unpkg.com/vue-router@3/dist/vue-router.js](https://unpkg.com/vue-router@3/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com)은 NPM 기반 CDN 링크를 제공합니다. 위의 링크는 항상 NPM의 최신 릴리스를 가리킵니다. `https://unpkg.com/vue-router@3.0.0/dist/vue-router.js`와 같이 URL을 통해 특정 버전 / 태그를 사용할 수도 있습니다. 9 | 10 | 11 | Vue 다음에 `vue-router`를 포함하면 자동으로 설치됩니다. 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### NPM 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | 모듈 시스템에서 사용하면 `Vue.use()`를 통해 명시적으로 라우터를 추가해야합니다. 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | 전역 스크립트 태그를 사용할 때는 이 작업을 하지 않아도 됩니다. 34 | 35 | ### 개발용 빌드 36 | 37 | 최신 dev 빌드를 사용하고 싶은 경우 GitHub에서 직접 복제하고 `vue-router`를 직접 빌드 해야 합니다. 38 | 39 | ``` bash 40 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 41 | cd node_modules/vue-router 42 | npm install 43 | npm run build 44 | ``` 45 | -------------------------------------------------------------------------------- /docs/ru/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Начать знакомство → 5 | actionLink: /ru/installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | Vue Router — официальная библиотека маршрутизации для [Vue.js](https://ru.vuejs.org/). Она глубоко интегрируется с Vue.js и позволяет легко создавать SPA-приложения. Включает следующие возможности: 10 | 11 | - Вложенные маршруты/представления 12 | - Модульная конфигурация маршрутизатора 13 | - Доступ к параметрам маршрута, query, wildcards 14 | - Анимация переходов представлений на основе Vue.js 15 | - Удобный контроль навигации 16 | - Автоматическое проставление активного CSS класса для ссылок 17 | - Режимы работы HTML5 history или хэш, с авто-переключением в IE9 18 | - Настраиваемое поведение прокрутки страницы 19 | 20 | [Начать знакомство](./guide/) или поиграться с [примерами](https://github.com/vuejs/vue-router/tree/dev/examples) (см. [`README.md`](https://github.com/vuejs/vue-router/) для их запуска). 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/ru/guide/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # Именованные маршруты 2 | 3 | Иногда удобнее определять маршрут по имени, особенно при привязке к маршруту или выполнении навигации. Вы можете указать для маршрута имя в опции `routes` при создании экземпляра маршрутизатора: 4 | 5 | ```js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/user/:userId', 10 | name: 'user', 11 | component: User 12 | } 13 | ] 14 | }) 15 | ``` 16 | 17 | Чтобы создать ссылку на именованный маршрут, вы можете передать объект во входной параметр `to` компонента `router-link`: 18 | 19 | ```html 20 | Пользователь 21 | ``` 22 | 23 | Тот же самый объект можно использовать и для программного вызова `router.push()`: 24 | 25 | ```js 26 | router.push({ name: 'user', params: { userId: 123 }}) 27 | ``` 28 | 29 | В обоих случаях в результате переход будет происходить на путь `/user/123`. 30 | 31 | Полный пример можно посмотреть [здесь](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). 32 | -------------------------------------------------------------------------------- /docs/ru/installation.md: -------------------------------------------------------------------------------- 1 | # Установка 2 | 3 | ## Скачивание напрямую / CDN 4 | 5 | [https://unpkg.com/vue-router@3/dist/vue-router.js](https://unpkg.com/vue-router@3/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) предоставляет CDN-ссылки для NPM-пакетов. Ссылка выше всегда указывает на самую последнюю версию Vue-router на NPM. Вы можете также использовать конкретную версию, используя ссылки вида `https://unpkg.com/vue-router@3.0.0/dist/vue-router.js`. 9 | 10 | 11 | Подключите `vue-router` после Vue, и установка произойдёт автоматически: 12 | 13 | ```html 14 | 15 | 16 | ``` 17 | 18 | ## npm 19 | 20 | ```bash 21 | npm install vue-router 22 | ``` 23 | 24 | При использовании модульной системы, необходимо явно обозначить использование роутера при помощи `Vue.use()`: 25 | 26 | ```js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | Это не требуется при подключении через глобальный тег `script`. 34 | 35 | ## Vue CLI 36 | 37 | Если проект развернут с использованием [Vue CLI](https://cli.vuejs.org/ru/), то можно добавить Vue Router в качестве плагина. Это позволит CLI сгенерировать код подключения, приведённый выше, а также добавить два маршрута для примера. **Операция установки перезапишет `App.vue`** в проекте, поэтому убедитесь что сделали резервную копию перед запуском команды: 38 | 39 | ```sh 40 | vue add router 41 | ``` 42 | 43 | ## Версия для разработки 44 | 45 | Если вы хотите использовать самую новую dev-сборку `vue-router`, то придётся вручную склонировать репозиторий с GitHub и запустить сборку: 46 | 47 | ```bash 48 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 49 | cd node_modules/vue-router 50 | npm install 51 | npm run build 52 | ``` 53 | -------------------------------------------------------------------------------- /docs/zh/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | home: true 3 | heroImage: /logo.png 4 | actionText: Get Started → 5 | actionLink: /zh/installation.html 6 | footer: MIT Licensed | Copyright © 2014-present Evan You, Eduardo San Martin Morote 7 | --- 8 | 9 | 10 | 11 | Vue Router 是 [Vue.js](http://cn.vuejs.org) 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有: 12 | 13 | - 嵌套的路由/视图表 14 | - 模块化的、基于组件的路由配置 15 | - 路由参数、查询、通配符 16 | - 基于 Vue.js 过渡系统的视图过渡效果 17 | - 细粒度的导航控制 18 | - 带有自动激活的 CSS class 的链接 19 | - HTML5 历史模式或 hash 模式,在 IE9 中自动降级 20 | - 自定义的滚动条行为 21 | 22 | 现在开始[起步](./guide/)或尝试一下我们的[示例](https://github.com/vuejs/vue-router/tree/dev/examples)吧 (查看仓库的 [`README.md`](https://github.com/vuejs/vue-router/) 来运行它们)。 23 | 24 | 25 | -------------------------------------------------------------------------------- /docs/zh/guide/advanced/lazy-loading.md: -------------------------------------------------------------------------------- 1 | # 路由懒加载 2 | 3 | 4 | 5 | 当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。 6 | 7 | 结合 Vue 的[异步组件](https://cn.vuejs.org/v2/guide/components-dynamic-async.html#异步组件)和 Webpack 的[代码分割功能](https://doc.webpack-china.org/guides/code-splitting-async/#require-ensure-/),轻松实现路由组件的懒加载。 8 | 9 | 首先,可以将异步组件定义为返回一个 Promise 的工厂函数 (该函数返回的 Promise 应该 resolve 组件本身): 10 | 11 | ```js 12 | const Foo = () => 13 | Promise.resolve({ 14 | /* 组件定义对象 */ 15 | }) 16 | ``` 17 | 18 | 第二,在 Webpack 2 中,我们可以使用[动态 import](https://github.com/tc39/proposal-dynamic-import)语法来定义代码分块点 (split point): 19 | 20 | ```js 21 | import('./Foo.vue') // 返回 Promise 22 | ``` 23 | 24 | ::: tip 注意 25 | 如果您使用的是 Babel,你将需要添加 [`syntax-dynamic-import`](https://babeljs.io/docs/plugins/syntax-dynamic-import/) 插件,才能使 Babel 可以正确地解析语法。 26 | ::: 27 | 28 | 结合这两者,这就是如何定义一个能够被 Webpack 自动代码分割的异步组件。 29 | 30 | ```js 31 | const Foo = () => import('./Foo.vue') 32 | ``` 33 | 34 | 在路由配置中什么都不需要改变,只需要像往常一样使用 `Foo`: 35 | 36 | ```js 37 | const router = new VueRouter({ 38 | routes: [{ path: '/foo', component: Foo }] 39 | }) 40 | ``` 41 | 42 | ## 把组件按组分块 43 | 44 | 有时候我们想把某个路由下的所有组件都打包在同个异步块 (chunk) 中。只需要使用 [命名 chunk](https://webpack.js.org/guides/code-splitting-require/#chunkname),一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4)。 45 | 46 | ```js 47 | const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') 48 | const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') 49 | const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') 50 | ``` 51 | 52 | Webpack 会将任何一个异步模块与相同的块名称组合到相同的异步块中。 53 | -------------------------------------------------------------------------------- /docs/zh/guide/advanced/meta.md: -------------------------------------------------------------------------------- 1 | # 路由元信息 2 | 3 | 定义路由的时候可以配置 `meta` 字段: 4 | 5 | ``` js 6 | const router = new VueRouter({ 7 | routes: [ 8 | { 9 | path: '/foo', 10 | component: Foo, 11 | children: [ 12 | { 13 | path: 'bar', 14 | component: Bar, 15 | // a meta field 16 | meta: { requiresAuth: true } 17 | } 18 | ] 19 | } 20 | ] 21 | }) 22 | ``` 23 | 24 | 那么如何访问这个 `meta` 字段呢? 25 | 26 | 首先,我们称呼 `routes` 配置中的每个路由对象为 **路由记录**。路由记录可以是嵌套的,因此,当一个路由匹配成功后,他可能匹配多个路由记录 27 | 28 | 例如,根据上面的路由配置,`/foo/bar` 这个 URL 将会匹配父路由记录以及子路由记录。 29 | 30 | 一个路由匹配到的所有路由记录会暴露为 `$route` 对象 (还有在导航守卫中的路由对象) 的 `$route.matched` 数组。因此,我们需要遍历 `$route.matched` 来检查路由记录中的 `meta` 字段。 31 | 32 | 下面例子展示在全局导航守卫中检查元字段: 33 | 34 | ``` js 35 | router.beforeEach((to, from, next) => { 36 | if (to.matched.some(record => record.meta.requiresAuth)) { 37 | // this route requires auth, check if logged in 38 | // if not, redirect to login page. 39 | if (!auth.loggedIn()) { 40 | next({ 41 | path: '/login', 42 | query: { redirect: to.fullPath } 43 | }) 44 | } else { 45 | next() 46 | } 47 | } else { 48 | next() // 确保一定要调用 next() 49 | } 50 | }) 51 | ``` 52 | -------------------------------------------------------------------------------- /docs/zh/guide/advanced/transitions.md: -------------------------------------------------------------------------------- 1 | # 过渡动效 2 | 3 | 4 | 5 | `` 是基本的动态组件,所以我们可以用 `` 组件给它添加一些过渡效果: 6 | 7 | ```html 8 | 9 | 10 | 11 | ``` 12 | 13 | [Transition 的所有功能](https://v2.cn.vuejs.org/v2/guide/transitions.html) 在这里同样适用。 14 | 15 | ## 单个路由的过渡 16 | 17 | 上面的用法会给所有路由设置一样的过渡效果,如果你想让每个路由组件有各自的过渡效果,可以在各路由组件内使用 `` 并设置不同的 name。 18 | 19 | ```js 20 | const Foo = { 21 | template: ` 22 | 23 |
...
24 |
25 | ` 26 | } 27 | 28 | const Bar = { 29 | template: ` 30 | 31 |
...
32 |
33 | ` 34 | } 35 | ``` 36 | 37 | ## 基于路由的动态过渡 38 | 39 | 还可以基于当前路由与目标路由的变化关系,动态设置过渡效果: 40 | 41 | ```html 42 | 43 | 44 | 45 | 46 | ``` 47 | 48 | ```js 49 | // 接着在父组件内 50 | // watch $route 决定使用哪种过渡 51 | watch: { 52 | '$route' (to, from) { 53 | const toDepth = to.path.split('/').length 54 | const fromDepth = from.path.split('/').length 55 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' 56 | } 57 | } 58 | ``` 59 | 60 | 查看完整例子请[移步这里](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js)。 61 | -------------------------------------------------------------------------------- /docs/zh/guide/essentials/named-routes.md: -------------------------------------------------------------------------------- 1 | # 命名路由 2 | 3 | 4 | 5 | 有时候,通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。你可以在创建 Router 实例的时候,在 `routes` 配置中给某个路由设置名称。 6 | 7 | ```js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { 11 | path: '/user/:userId', 12 | name: 'user', 13 | component: User 14 | } 15 | ] 16 | }) 17 | ``` 18 | 19 | 要链接到一个命名路由,可以给 `router-link` 的 `to` 属性传一个对象: 20 | 21 | ```html 22 | User 23 | ``` 24 | 25 | 这跟代码调用 `router.push()` 是一回事: 26 | 27 | ```js 28 | router.push({ name: 'user', params: { userId: 123 } }) 29 | ``` 30 | 31 | 这两种方式都会把路由导航到 `/user/123` 路径。 32 | 33 | 完整的例子请[移步这里](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js)。 34 | -------------------------------------------------------------------------------- /docs/zh/guide/essentials/redirect-and-alias.md: -------------------------------------------------------------------------------- 1 | # 重定向和别名 2 | 3 | ## 重定向 4 | 5 | 重定向也是通过 `routes` 配置来完成,下面例子是从 `/a` 重定向到 `/b`: 6 | 7 | ``` js 8 | const router = new VueRouter({ 9 | routes: [ 10 | { path: '/a', redirect: '/b' } 11 | ] 12 | }) 13 | ``` 14 | 15 | 重定向的目标也可以是一个命名的路由: 16 | 17 | ``` js 18 | const router = new VueRouter({ 19 | routes: [ 20 | { path: '/a', redirect: { name: 'foo' }} 21 | ] 22 | }) 23 | ``` 24 | 25 | 甚至是一个方法,动态返回重定向目标: 26 | 27 | ``` js 28 | const router = new VueRouter({ 29 | routes: [ 30 | { path: '/a', redirect: to => { 31 | // 方法接收 目标路由 作为参数 32 | // return 重定向的 字符串路径/路径对象 33 | }} 34 | ] 35 | }) 36 | ``` 37 | 38 | 注意[导航守卫](../advanced/navigation-guards.md)并没有应用在跳转路由上,而仅仅应用在其目标上。在下面这个例子中,为 `/a` 路由添加一个 `beforeEnter` 守卫并不会有任何效果。 39 | 40 | 其它高级用法,请参考[例子](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js)。 41 | 42 | ## 别名 43 | 44 | “重定向”的意思是,当用户访问 `/a`时,URL 将会被替换成 `/b`,然后匹配路由为 `/b`,那么“别名”又是什么呢? 45 | 46 | **`/a` 的别名是 `/b`,意味着,当用户访问 `/b` 时,URL 会保持为 `/b`,但是路由匹配则为 `/a`,就像用户访问 `/a` 一样。** 47 | 48 | 上面对应的路由配置为: 49 | 50 | ``` js 51 | const router = new VueRouter({ 52 | routes: [ 53 | { path: '/a', component: A, alias: '/b' } 54 | ] 55 | }) 56 | ``` 57 | 58 | “别名”的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构。 59 | 60 | 更多高级用法,请查看[例子](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js)。 61 | -------------------------------------------------------------------------------- /docs/zh/installation.md: -------------------------------------------------------------------------------- 1 | # 安装 2 | 3 | ### 直接下载 / CDN 4 | 5 | [https://unpkg.com/vue-router@3/dist/vue-router.js](https://unpkg.com/vue-router@3/dist/vue-router.js) 6 | 7 | 8 | [Unpkg.com](https://unpkg.com) 提供了基于 NPM 的 CDN 链接。上面的链接会一直指向在 NPM 发布的最新版本。你也可以像 `https://unpkg.com/vue-router@3.0.0/dist/vue-router.js` 这样指定 版本号 或者 Tag。 9 | 10 | 11 | 在 Vue 后面加载 `vue-router`,它会自动安装的: 12 | 13 | ``` html 14 | 15 | 16 | ``` 17 | 18 | ### NPM 19 | 20 | ``` bash 21 | npm install vue-router 22 | ``` 23 | 24 | 如果在一个模块化工程中使用它,必须要通过 `Vue.use()` 明确地安装路由功能: 25 | 26 | ``` js 27 | import Vue from 'vue' 28 | import VueRouter from 'vue-router' 29 | 30 | Vue.use(VueRouter) 31 | ``` 32 | 33 | 如果使用全局的 script 标签,则无须如此 (手动安装)。 34 | 35 | ### Vue CLI 36 | 37 | 如果你有一个正在使用 [Vue CLI](https://cli.vuejs.org/zh/) 的项目,你可以以项目插件的形式添加 Vue Router。CLI 可以生成上述代码及两个示例路由。**它也会覆盖你的 `App.vue`**,因此请确保在项目中运行以下命令之前备份这个文件: 38 | 39 | ```sh 40 | vue add router 41 | ``` 42 | 43 | ### 构建开发版 44 | 45 | 如果你想使用最新的开发版,就得从 GitHub 上直接 clone,然后自己 build 一个 `vue-router`。 46 | 47 | ``` bash 48 | git clone https://github.com/vuejs/vue-router.git node_modules/vue-router 49 | cd node_modules/vue-router 50 | npm install 51 | npm run build 52 | ``` 53 | -------------------------------------------------------------------------------- /examples/active-links/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | ← Examples index 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/auth-flow/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | import auth from './auth' 7 | import App from './components/App.vue' 8 | import About from './components/About.vue' 9 | import Dashboard from './components/Dashboard.vue' 10 | import Login from './components/Login.vue' 11 | 12 | function requireAuth (to, from, next) { 13 | if (!auth.loggedIn()) { 14 | next({ 15 | path: '/login', 16 | query: { redirect: to.fullPath } 17 | }) 18 | } else { 19 | next() 20 | } 21 | } 22 | 23 | const router = new VueRouter({ 24 | mode: 'history', 25 | base: __dirname, 26 | routes: [ 27 | { path: '/about', component: About }, 28 | { path: '/dashboard', component: Dashboard, beforeEnter: requireAuth }, 29 | { path: '/login', component: Login }, 30 | { path: '/logout', 31 | beforeEnter (to, from, next) { 32 | auth.logout() 33 | next('/') 34 | } 35 | } 36 | ] 37 | }) 38 | 39 | /* eslint-disable no-new */ 40 | new Vue({ 41 | el: '#app', 42 | router, 43 | // replace the content of
with App 44 | render: h => h(App) 45 | }) 46 | -------------------------------------------------------------------------------- /examples/auth-flow/auth.js: -------------------------------------------------------------------------------- 1 | /* globals localStorage */ 2 | 3 | export default { 4 | login (email, pass, cb) { 5 | cb = arguments[arguments.length - 1] 6 | if (localStorage.token) { 7 | if (cb) cb(true) 8 | this.onChange(true) 9 | return 10 | } 11 | pretendRequest(email, pass, (res) => { 12 | if (res.authenticated) { 13 | localStorage.token = res.token 14 | if (cb) cb(true) 15 | this.onChange(true) 16 | } else { 17 | if (cb) cb(false) 18 | this.onChange(false) 19 | } 20 | }) 21 | }, 22 | 23 | getToken () { 24 | return localStorage.token 25 | }, 26 | 27 | logout (cb) { 28 | delete localStorage.token 29 | if (cb) cb() 30 | this.onChange(false) 31 | }, 32 | 33 | loggedIn () { 34 | return !!localStorage.token 35 | }, 36 | 37 | onChange () {} 38 | } 39 | 40 | function pretendRequest (email, pass, cb) { 41 | setTimeout(() => { 42 | if (email === 'joe@example.com' && pass === 'password1') { 43 | cb({ 44 | authenticated: true, 45 | token: Math.random().toString(36).substring(7) 46 | }) 47 | } else { 48 | cb({ authenticated: false }) 49 | } 50 | }, 0) 51 | } 52 | -------------------------------------------------------------------------------- /examples/auth-flow/components/About.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /examples/auth-flow/components/App.vue: -------------------------------------------------------------------------------- 1 | 25 | 26 | 42 | -------------------------------------------------------------------------------- /examples/auth-flow/components/Dashboard.vue: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /examples/auth-flow/components/Login.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 40 | 41 | 46 | -------------------------------------------------------------------------------- /examples/auth-flow/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/basic/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 | 5 |
6 |
7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/composables/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 |
6 | 7 | 8 | -------------------------------------------------------------------------------- /examples/data-fetching/Post.vue: -------------------------------------------------------------------------------- 1 | 19 | 20 | 53 | 54 | 76 | -------------------------------------------------------------------------------- /examples/data-fetching/api.js: -------------------------------------------------------------------------------- 1 | const posts = { 2 | '1': { 3 | id: 1, 4 | title: 'sunt aut facere', 5 | body: 'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto' 6 | }, 7 | '2': { 8 | id: 2, 9 | title: 'qui est esse', 10 | body: 'est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla' 11 | } 12 | } 13 | 14 | export function getPost (id, cb) { 15 | // fake an API request 16 | setTimeout(() => { 17 | if (posts[id]) { 18 | cb(null, posts[id]) 19 | } else { 20 | cb(new Error('Post not found.')) 21 | } 22 | }, 100) 23 | } 24 | -------------------------------------------------------------------------------- /examples/data-fetching/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | import Post from './Post.vue' 4 | 5 | Vue.use(VueRouter) 6 | 7 | const Home = { template: '
home
' } 8 | 9 | const router = new VueRouter({ 10 | mode: 'history', 11 | base: __dirname, 12 | routes: [ 13 | { path: '/', component: Home }, 14 | { path: '/post/:id', component: Post } 15 | ] 16 | }) 17 | 18 | new Vue({ 19 | router, 20 | template: ` 21 |
22 |

Data Fetching

23 |
    24 |
  • /
  • 25 |
  • /post/1
  • 26 |
  • /post/2
  • 27 |
  • /post/3
  • 28 |
29 | 30 |
31 | ` 32 | }).$mount('#app') 33 | -------------------------------------------------------------------------------- /examples/data-fetching/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/discrete-components/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | // 1. Use plugin. 5 | // This installs and , 6 | // and injects $router and $route to all router-enabled child components 7 | Vue.use(VueRouter) 8 | 9 | // 2. Define route components 10 | const Home = { template: '
Component: home
' } 11 | const Foo = { template: '
Component: foo
' } 12 | const Bar = { template: '
Component: bar
' } 13 | 14 | // 3. Create the router 15 | const router = new VueRouter({ 16 | mode: 'history', 17 | base: __dirname, 18 | routes: [ 19 | { path: '/', component: Home }, 20 | { path: '/foo', component: Foo }, 21 | { path: '/bar', component: Bar } 22 | ] 23 | }) 24 | 25 | // 4. Create extended base Vue with router injected here (all 26 | // children should inherit the same router). 27 | const BaseVue = Vue.extend({ router }) 28 | 29 | // Discrete components means that a new Vue instance will be created 30 | // and bound on multiple *independent* nodes (eg. one Vue instance 31 | // per node); but the router should act as a singleton and keep all 32 | // instances in sync. 33 | Array.prototype.forEach.call(document.querySelectorAll('.app'), (node) => { 34 | new BaseVue({ 35 | el: node 36 | }) 37 | }) 38 | -------------------------------------------------------------------------------- /examples/discrete-components/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | ← Examples index 10 |
11 |
12 |
    13 |
  • /
  • 14 |
  • /foo
  • 15 |
  • /bar
  • 16 |
17 | $route.path value: {{ $route.path }} 18 |
19 |
20 |
    21 |
  • /
  • 22 |
  • /foo
  • 23 |
  • /bar
  • 24 |
25 | $route.path value: {{ $route.path }} 26 |
27 |
28 |
    29 |
  • /
  • 30 |
  • /foo
  • 31 |
  • /bar
  • 32 |
33 | $route.path value: {{ $route.path }} 34 |
35 |
36 |
37 | 38 | $route.path value: {{ $route.path }} 39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /examples/global.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; 3 | color: #2c3e50; 4 | } 5 | 6 | #app { 7 | padding: 0 20px; 8 | } 9 | 10 | ul { 11 | line-height: 1.5em; 12 | padding-left: 1.5em; 13 | } 14 | 15 | a { 16 | color: #7f8c8d; 17 | text-decoration: none; 18 | } 19 | 20 | a:hover { 21 | color: #4fc08d; 22 | } 23 | -------------------------------------------------------------------------------- /examples/hash-mode/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 | 5 |
6 |
7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/hash-scroll-behavior/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | ← Examples index 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /examples/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Vue Router Examples 5 | 6 | 7 | 8 |

Vue Router Examples

9 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /examples/keepalive-view/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/lazy-loading-before-mount/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | const Home = { template: '
Home
' } 7 | const Foo = () => 8 | new Promise(resolve => { 9 | setTimeout(() => 10 | resolve({ 11 | template: `
This is Foo
` 12 | }) 13 | , 10) 14 | }) 15 | 16 | const router = new VueRouter({ 17 | mode: 'history', 18 | base: __dirname, 19 | routes: [ 20 | { path: '/', component: Home }, 21 | // Just use them normally in the route config 22 | { path: '/async', component: Foo } 23 | ] 24 | }) 25 | 26 | router.onReady(() => { 27 | router.push('/async') 28 | }) 29 | 30 | document.getElementById('load-button').addEventListener('click', (event) => { 31 | new Vue({ 32 | router, 33 | template: ` 34 |
35 |

Async

36 | 37 |
38 | ` 39 | }).$mount('#app') 40 | event.target.remove() 41 | }) 42 | -------------------------------------------------------------------------------- /examples/lazy-loading-before-mount/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/lazy-loading/Bar.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 16 | -------------------------------------------------------------------------------- /examples/lazy-loading/Baz.vue: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /examples/lazy-loading/Foo.vue: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /examples/lazy-loading/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/multi-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | popstate count: 18 | 19 |
20 |
21 |
22 | 23 | 24 | -------------------------------------------------------------------------------- /examples/named-routes/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | const Home = { template: '
This is Home
' } 7 | const Foo = { template: '
This is Foo
' } 8 | const Bar = { template: '
This is Bar {{ $route.params.id }}
' } 9 | 10 | const router = new VueRouter({ 11 | mode: 'history', 12 | base: __dirname, 13 | routes: [ 14 | { path: '/', name: 'home', component: Home }, 15 | { path: '/foo', name: 'foo', component: Foo }, 16 | { path: '/bar/:id', name: 'bar', component: Bar } 17 | ] 18 | }) 19 | 20 | new Vue({ 21 | router, 22 | template: ` 23 |
24 |

Named Routes

25 |

Current route name: {{ $route.name }}

26 |
    27 |
  • home
  • 28 |
  • foo
  • 29 |
  • bar
  • 30 |
31 | 32 |
33 | ` 34 | }).$mount('#app') 35 | -------------------------------------------------------------------------------- /examples/named-routes/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/named-views/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | const Foo = { template: '
foo
' } 7 | const Bar = { template: '
bar
' } 8 | const Baz = { template: '
baz
' } 9 | 10 | const router = new VueRouter({ 11 | mode: 'history', 12 | base: __dirname, 13 | routes: [ 14 | { path: '/', 15 | // a single route can define multiple named components 16 | // which will be rendered into s with corresponding names. 17 | components: { 18 | default: Foo, 19 | a: Bar, 20 | b: Baz 21 | } 22 | }, 23 | { 24 | path: '/other', 25 | components: { 26 | default: Baz, 27 | a: Bar, 28 | b: Foo 29 | } 30 | } 31 | ] 32 | }) 33 | 34 | new Vue({ 35 | router, 36 | template: ` 37 |
38 |

Named Views

39 |
    40 |
  • /
  • 41 |
  • /other
  • 42 |
43 | 44 | 45 | 46 |
47 | ` 48 | }).$mount('#app') 49 | -------------------------------------------------------------------------------- /examples/named-views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/navigation-guards/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | ← Examples index 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/nested-router/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | const Foo = { template: `

foo

` } 7 | const Bar = { template: `

bar

` } 8 | 9 | const childRouter = new VueRouter({ 10 | mode: 'abstract', 11 | routes: [ 12 | { path: '/foo', component: Foo }, 13 | { path: '/bar', component: Bar } 14 | ] 15 | }) 16 | 17 | const Nested = { 18 | router: childRouter, 19 | template: `
20 |

Child router path: {{ $route.fullPath }}

21 |
    22 |
  • /foo
  • 23 |
  • /bar
  • 24 |
25 | 26 |
` 27 | } 28 | 29 | const router = new VueRouter({ 30 | mode: 'history', 31 | base: __dirname, 32 | routes: [ 33 | { path: '/nested-router', component: Nested }, 34 | { path: '/foo', component: Foo }, 35 | { path: '/bar', component: Bar } 36 | ] 37 | }) 38 | 39 | new Vue({ 40 | router, 41 | template: ` 42 |
43 |

Root router path: {{ $route.fullPath }}

44 |
    45 |
  • /nested-router
  • 46 |
  • /foo
  • 47 |
  • /bar
  • 48 |
49 | 50 |
51 | ` 52 | }).$mount('#app') 53 | -------------------------------------------------------------------------------- /examples/nested-router/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | ← Examples index 8 |
9 | 10 | 11 | -------------------------------------------------------------------------------- /examples/nested-routes/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | ← Examples index 14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /examples/redirect/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/restart-app/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | const Home = { template: '
home
' } 5 | const Foo = { template: '
foo
' } 6 | 7 | const routes = [ 8 | { path: '/', component: Home }, 9 | { path: '/foo', component: Foo } 10 | ] 11 | 12 | const router = new VueRouter({ 13 | mode: 'history', 14 | base: __dirname, 15 | routes 16 | }) 17 | 18 | // track number of beforeResolve 19 | const increment = name => { 20 | const counter = document.getElementById(name) 21 | counter.innerHTML++ 22 | } 23 | 24 | document.getElementById('beforeEach').innerHTML = 0 25 | router.beforeEach((to, from, next) => { 26 | increment('beforeEach') 27 | next() 28 | }) 29 | 30 | document.getElementById('beforeResolve').innerHTML = 0 31 | router.beforeResolve((to, from, next) => { 32 | increment('beforeResolve') 33 | next() 34 | }) 35 | 36 | document.getElementById('afterEach').innerHTML = 0 37 | router.afterEach((to, from) => { 38 | increment('afterEach') 39 | }) 40 | 41 | Vue.use(VueRouter) 42 | 43 | let vueInstance 44 | const mountEl = document.getElementById('mount') 45 | const unmountEl = document.getElementById('unmount') 46 | 47 | mountEl.addEventListener('click', () => { 48 | vueInstance = new Vue({ 49 | router, 50 | template: ` 51 |
52 |

Hello "Restart-app"

53 |
    54 |
  • Go to Home
  • 55 |
  • Go to Foo
  • 56 |
57 | 58 |
59 | ` 60 | }).$mount('#app') 61 | }) 62 | 63 | unmountEl.addEventListener('click', () => { 64 | vueInstance.$destroy() 65 | vueInstance.$el.innerHTML = '' 66 | }) 67 | -------------------------------------------------------------------------------- /examples/restart-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 | 5 |
6 | 7 | 8 | 9 | 10 |
11 | 12 | Count beforeEach:
13 | Count beforeResolve:
14 | Count afterEach:
15 | 16 |
17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /examples/route-alias/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/route-matching/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/route-params/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | Vue.use(VueRouter) 5 | 6 | const Log = { 7 | template: `
id: {{ $route.params.id }}, type: {{ $route.params.type }}
` 8 | } 9 | 10 | const Logs = { 11 | template: ` 12 |
13 |
{{ to.params }}
14 | {{ to.params.type }} 15 | 16 |
17 | `, 18 | data () { 19 | return { 20 | to: { 21 | name: 'items.logs.type', 22 | params: { type: 'info' } 23 | } 24 | } 25 | } 26 | } 27 | 28 | const router = new VueRouter({ 29 | mode: 'history', 30 | base: __dirname, 31 | routes: [ 32 | { 33 | path: '/items/:id/logs', 34 | component: Logs, 35 | children: [ 36 | { 37 | path: ':type', 38 | name: 'items.logs.type', 39 | component: Log 40 | } 41 | ] 42 | } 43 | ] 44 | }) 45 | 46 | new Vue({ 47 | router, 48 | template: ` 49 |
50 |

Route params

51 |
    52 |
  • item #1
  • 53 |
  • item #2
  • 54 |
55 | 56 |
57 | ` 58 | }).$mount('#app') 59 | -------------------------------------------------------------------------------- /examples/route-params/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/route-props/Hello.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 18 | -------------------------------------------------------------------------------- /examples/route-props/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | import Hello from './Hello.vue' 4 | 5 | Vue.use(VueRouter) 6 | 7 | function dynamicPropsFn (route) { 8 | const now = new Date() 9 | return { 10 | name: (now.getFullYear() + parseInt(route.params.years)) + '!' 11 | } 12 | } 13 | 14 | const router = new VueRouter({ 15 | mode: 'history', 16 | base: __dirname, 17 | routes: [ 18 | { path: '/', component: Hello }, // No props, no nothing 19 | { path: '/hello/:name', component: Hello, props: true }, // Pass route.params to props 20 | { path: '/static', component: Hello, props: { name: 'world' }}, // static values 21 | { path: '/dynamic/:years', component: Hello, props: dynamicPropsFn }, // custom logic for mapping between route and props 22 | { path: '/attrs', component: Hello, props: { name: 'attrs' }} 23 | ] 24 | }) 25 | 26 | new Vue({ 27 | router, 28 | template: ` 29 |
30 |

Route props

31 |
    32 |
  • /
  • 33 |
  • /hello/you
  • 34 |
  • /static
  • 35 |
  • /dynamic/1
  • 36 |
  • /attrs
  • 37 |
38 | 39 |
40 | ` 41 | }).$mount('#app') 42 | -------------------------------------------------------------------------------- /examples/route-props/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ← Examples index 4 |
5 | 6 | 7 | -------------------------------------------------------------------------------- /examples/router-errors/app.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | 4 | const component = { 5 | template: ` 6 |
7 | {{ $route.fullPath }} 8 |
9 | ` 10 | } 11 | 12 | Vue.use(VueRouter) 13 | 14 | const router = new VueRouter({ 15 | routes: [ 16 | { path: '/', component }, { path: '/foo', component } 17 | ] 18 | }) 19 | 20 | window.router = router 21 | 22 | router.beforeEach((to, from, next) => { 23 | console.log('from', from.fullPath) 24 | console.log('going to', to.fullPath) 25 | if (to.query.wait) { 26 | setTimeout(() => next(), 100) 27 | } else if (to.query.redirect) { 28 | next(to.query.redirect) 29 | } else if (to.query.abort) { 30 | next(false) 31 | } else { 32 | next() 33 | } 34 | }) 35 | 36 | new Vue({ 37 | el: '#app', 38 | router 39 | }) 40 | 41 | // 4 NAVIGATION ERROR CASES : 42 | 43 | // navigation duplicated 44 | // router.push('/foo') 45 | // router.push('/foo') 46 | 47 | // navigation cancelled 48 | // router.push('/foo?wait=y') 49 | // router.push('/') 50 | 51 | // navigation redirected 52 | // router.push('/foo?redirect=/') 53 | 54 | // navigation aborted 55 | // router.push('/foo?abort=y') 56 | -------------------------------------------------------------------------------- /examples/router-errors/index.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | / 4 | /foo 5 | 6 |
7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/scroll-behavior/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 18 | ← Examples index 19 |
20 | 21 | 22 | -------------------------------------------------------------------------------- /examples/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const rewrite = require('express-urlrewrite') 3 | const webpack = require('webpack') 4 | const webpackDevMiddleware = require('webpack-dev-middleware') 5 | const WebpackConfig = require('./webpack.config') 6 | 7 | const app = express() 8 | 9 | app.use( 10 | webpackDevMiddleware(webpack(WebpackConfig), { 11 | publicPath: '/__build__/', 12 | stats: { 13 | colors: true, 14 | chunks: false 15 | } 16 | }) 17 | ) 18 | 19 | const fs = require('fs') 20 | const path = require('path') 21 | 22 | fs.readdirSync(__dirname).forEach(file => { 23 | if (fs.statSync(path.join(__dirname, file)).isDirectory()) { 24 | app.use(rewrite('/' + file + '/*', '/' + file + '/index.html')) 25 | } 26 | }) 27 | 28 | app.use(express.static(__dirname)) 29 | 30 | const host = process.env.HOST || 'localhost' 31 | const port = process.env.PORT || 8080 32 | module.exports = app.listen(port, host, () => { 33 | console.log(`Server listening on http://${host}:${port}, Ctrl+C to stop`) 34 | }) 35 | -------------------------------------------------------------------------------- /examples/transitions/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 25 | ← Examples index 26 |
27 | 28 | 29 | -------------------------------------------------------------------------------- /examples/webpack.config.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const path = require('path') 3 | const VuePlugin = require('vue-loader/lib/plugin') 4 | 5 | module.exports = { 6 | // Expose __dirname to allow automatically setting basename. 7 | context: __dirname, 8 | node: { 9 | __dirname: true 10 | }, 11 | 12 | mode: process.env.NODE_ENV || 'development', 13 | 14 | entry: fs.readdirSync(__dirname).reduce((entries, dir) => { 15 | const fullDir = path.join(__dirname, dir) 16 | const entry = path.join(fullDir, 'app.js') 17 | if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) { 18 | entries[dir] = ['es6-promise/auto', entry] 19 | } 20 | 21 | return entries 22 | }, {}), 23 | 24 | output: { 25 | path: path.join(__dirname, '__build__'), 26 | filename: '[name].js', 27 | chunkFilename: '[id].chunk.js', 28 | publicPath: '/__build__/' 29 | }, 30 | 31 | module: { 32 | rules: [ 33 | { 34 | test: /\.js$/, 35 | exclude: /node_modules/, 36 | use: 'babel-loader' 37 | }, 38 | { 39 | test: /\.vue$/, 40 | use: 'vue-loader' 41 | }, 42 | { 43 | test: /\.css$/, 44 | use: ['vue-style-loader', 'css-loader'] 45 | } 46 | ] 47 | }, 48 | 49 | resolve: { 50 | alias: { 51 | vue: 'vue/dist/vue.esm.js', 52 | 'vue-router': path.join(__dirname, '..', 'src'), 53 | 'vue-router/composables': path.join(__dirname, '..', 'src/composables') 54 | } 55 | }, 56 | 57 | optimization: { 58 | splitChunks: { 59 | cacheGroups: { 60 | shared: { 61 | name: 'shared', 62 | chunks: 'initial', 63 | minChunks: 2 64 | } 65 | } 66 | } 67 | }, 68 | 69 | plugins: [new VuePlugin()] 70 | } 71 | -------------------------------------------------------------------------------- /netlify.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | ignore = "git diff --quiet HEAD^ HEAD ./docs/" 3 | publish = "docs/.vuepress/dist" 4 | command = "yarn run docs:build" 5 | -------------------------------------------------------------------------------- /scripts/release.sh: -------------------------------------------------------------------------------- 1 | set -e 2 | echo "Current version:" $(grep version package.json | sed -E 's/^.*"(4[^"]+)".*$/\1/') 3 | echo "Enter release version e.g. 3.3.0: " 4 | read VERSION 5 | 6 | read -p "Releasing v$VERSION - are you sure? (y/n)" -n 1 -r 7 | echo # (optional) move to a new line 8 | if [[ $REPLY =~ ^[Yy]$ ]] 9 | then 10 | echo "Releasing v$VERSION ..." 11 | 12 | # commit 13 | VERSION=$VERSION npm run build 14 | git add dist composables.* 15 | git commit -m "build: bundle $VERSION" 16 | npm version $VERSION --message "chore(release): %s" 17 | 18 | # changelog 19 | npm run changelog 20 | echo "Please check the git history and the changelog and press enter" 21 | read OKAY 22 | git add CHANGELOG.md 23 | git commit -m "chore(changelog): $VERSION" 24 | 25 | # publish 26 | git push origin refs/tags/v$VERSION 27 | git push 28 | npm publish --tag legacy 29 | fi 30 | -------------------------------------------------------------------------------- /scripts/verifyCommitMsg.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk') // eslint-disable-line 2 | const msgPath = process.env.GIT_PARAMS 3 | const msg = require('fs').readFileSync(msgPath, 'utf-8').trim() 4 | 5 | const commitRE = /^(v\d+\.\d+\.\d+(-(alpha|beta|rc.\d+))?$)|((revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|ci|chore|types|build)(\(.+\))?: .{1,50})/ 6 | 7 | if (!commitRE.test(msg)) { 8 | console.log() 9 | console.error( 10 | ` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` + 11 | chalk.red(` Proper commit message format is required for automated changelog generation. Examples:\n\n`) + 12 | ` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` + 13 | ` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` + 14 | chalk.red(` See .github/COMMIT_CONVENTION.md for more details.\n`) + 15 | chalk.red(` You can also use ${chalk.cyan(`npm run commit`)} to interactively generate a commit message.\n`) 16 | ) 17 | process.exit(1) 18 | } 19 | -------------------------------------------------------------------------------- /src/composables/globals.js: -------------------------------------------------------------------------------- 1 | import { 2 | getCurrentInstance, 3 | shallowReactive, 4 | effectScope 5 | } from 'vue' 6 | import { throwNoCurrentInstance } from './utils' 7 | 8 | export function useRouter () { 9 | if (process.env.NODE_ENV !== 'production') { 10 | throwNoCurrentInstance('useRouter') 11 | } 12 | 13 | return getCurrentInstance().proxy.$root.$router 14 | } 15 | 16 | export function useRoute () { 17 | if (process.env.NODE_ENV !== 'production') { 18 | throwNoCurrentInstance('useRoute') 19 | } 20 | 21 | const root = getCurrentInstance().proxy.$root 22 | if (!root._$route) { 23 | const route = effectScope(true).run(() => 24 | shallowReactive(Object.assign({}, root.$router.currentRoute)) 25 | ) 26 | root._$route = route 27 | 28 | root.$router.afterEach(to => { 29 | Object.assign(route, to) 30 | }) 31 | } 32 | 33 | return root._$route 34 | } 35 | -------------------------------------------------------------------------------- /src/composables/index.js: -------------------------------------------------------------------------------- 1 | export * from './guards' 2 | export * from './globals' 3 | export * from './useLink' 4 | -------------------------------------------------------------------------------- /src/composables/utils.js: -------------------------------------------------------------------------------- 1 | import { getCurrentInstance } from 'vue' 2 | 3 | // dev only warn if no current instance 4 | 5 | export function throwNoCurrentInstance (method) { 6 | if (!getCurrentInstance()) { 7 | throw new Error( 8 | `[vue-router]: Missing current instance. ${method}() must be called inside