├── docs
├── old
│ ├── SUMMARY.md
│ └── README.md
├── de
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ ├── options.md
│ │ └── router-instance.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ └── redirect-and-alias.md
│ ├── installation.md
│ ├── SUMMARY.md
│ └── advanced
│ │ ├── meta.md
│ │ └── transitions.md
├── assets
│ ├── CNAME
│ └── circle.yml
├── en
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ ├── options.md
│ │ └── router-instance.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ └── redirect-and-alias.md
│ ├── installation.md
│ ├── SUMMARY.md
│ └── advanced
│ │ ├── meta.md
│ │ ├── transitions.md
│ │ ├── lazy-loading.md
│ │ └── scroll-behavior.md
├── ja
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ ├── router-instance.md
│ │ ├── options.md
│ │ └── route-object.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ ├── redirect-and-alias.md
│ │ ├── history-mode.md
│ │ ├── passing-props.md
│ │ └── getting-started.md
│ ├── installation.md
│ ├── advanced
│ │ ├── meta.md
│ │ ├── transitions.md
│ │ ├── lazy-loading.md
│ │ └── scroll-behavior.md
│ └── SUMMARY.md
├── kr
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ ├── router-instance.md
│ │ ├── options.md
│ │ └── route-object.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ ├── redirect-and-alias.md
│ │ ├── passing-props.md
│ │ ├── history-mode.md
│ │ └── getting-started.md
│ ├── installation.md
│ ├── SUMMARY.md
│ └── advanced
│ │ ├── meta.md
│ │ ├── transitions.md
│ │ ├── lazy-loading.md
│ │ └── scroll-behavior.md
├── ru
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ └── router-instance.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ └── redirect-and-alias.md
│ ├── installation.md
│ ├── SUMMARY.md
│ └── advanced
│ │ ├── meta.md
│ │ ├── transitions.md
│ │ └── lazy-loading.md
├── zh-cn
│ ├── README.md
│ ├── api
│ │ ├── component-injections.md
│ │ ├── router-view.md
│ │ ├── router-instance.md
│ │ ├── options.md
│ │ └── route-object.md
│ ├── essentials
│ │ ├── named-routes.md
│ │ ├── named-views.md
│ │ ├── redirect-and-alias.md
│ │ ├── history-mode.md
│ │ ├── getting-started.md
│ │ ├── navigation.md
│ │ └── dynamic-matching.md
│ ├── installation.md
│ ├── SUMMARY.md
│ └── advanced
│ │ ├── meta.md
│ │ ├── transitions.md
│ │ ├── scroll-behavior.md
│ │ └── lazy-loading.md
├── LANGS.md
└── book.json
├── circle.yml
├── types
├── typings.json
├── test
│ └── tsconfig.json
├── vue.d.ts
└── index.d.ts
├── src
├── util
│ ├── dom.js
│ ├── warn.js
│ ├── async.js
│ ├── params.js
│ ├── push-state.js
│ ├── path.js
│ └── location.js
├── install.js
└── history
│ ├── abstract.js
│ └── html5.js
├── .babelrc
├── examples
├── auth-flow
│ ├── components
│ │ ├── About.vue
│ │ ├── Dashboard.vue
│ │ ├── App.vue
│ │ └── Login.vue
│ ├── index.html
│ ├── app.js
│ └── auth.js
├── lazy-loading
│ ├── Baz.vue
│ ├── Foo.vue
│ ├── index.html
│ └── Bar.vue
├── basic
│ ├── index.html
│ └── app.js
├── redirect
│ └── index.html
├── hash-mode
│ ├── index.html
│ └── app.js
├── named-views
│ ├── index.html
│ └── app.js
├── route-alias
│ └── index.html
├── route-props
│ ├── index.html
│ ├── Hello.vue
│ └── app.js
├── data-fetching
│ ├── index.html
│ ├── api.js
│ ├── app.js
│ └── Post.vue
├── named-routes
│ ├── index.html
│ └── app.js
├── route-matching
│ ├── index.html
│ └── app.js
├── navigation-guards
│ └── index.html
├── scroll-behavior
│ ├── index.html
│ └── app.js
├── active-links
│ └── index.html
├── nested-routes
│ └── index.html
├── global.css
├── transitions
│ ├── index.html
│ └── app.js
├── server.js
├── index.html
├── discrete-components
│ ├── app.js
│ └── index.html
└── webpack.config.js
├── .github
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── test
├── unit
│ ├── jasmine.json
│ └── specs
│ │ ├── async.spec.js
│ │ ├── discrete-components.spec.js
│ │ ├── query.spec.js
│ │ ├── node.spec.js
│ │ ├── create-matcher.spec.js
│ │ ├── create-map.spec.js
│ │ └── path.spec.js
└── e2e
│ ├── specs
│ ├── route-props.js
│ ├── data-fetching.js
│ ├── lazy-loading.js
│ ├── hash-mode.js
│ ├── named-views.js
│ ├── basic.js
│ ├── named-routes.js
│ ├── scroll-behavior.js
│ ├── transitions.js
│ └── active-links.js
│ ├── runner.js
│ └── nightwatch.config.js
├── .flowconfig
├── .eslintrc
├── bower.json
├── LICENSE
└── flow
└── declarations.js
/docs/old/SUMMARY.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/docs/de/README.md:
--------------------------------------------------------------------------------
1 | SUMMARY.md
--------------------------------------------------------------------------------
/docs/assets/CNAME:
--------------------------------------------------------------------------------
1 | router.vuejs.org
2 |
--------------------------------------------------------------------------------
/docs/en/README.md:
--------------------------------------------------------------------------------
1 | {% include "./SUMMARY.md" %}
2 |
--------------------------------------------------------------------------------
/docs/ja/README.md:
--------------------------------------------------------------------------------
1 | {% include "./SUMMARY.md" %}
2 |
--------------------------------------------------------------------------------
/docs/kr/README.md:
--------------------------------------------------------------------------------
1 | {% include "./SUMMARY.md" %}
2 |
--------------------------------------------------------------------------------
/docs/ru/README.md:
--------------------------------------------------------------------------------
1 | {% include "./SUMMARY.md" %}
2 |
--------------------------------------------------------------------------------
/docs/zh-cn/README.md:
--------------------------------------------------------------------------------
1 | {% include "./SUMMARY.md" %}
2 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | machine:
2 | node:
3 | version: 7
4 |
--------------------------------------------------------------------------------
/docs/assets/circle.yml:
--------------------------------------------------------------------------------
1 | general:
2 | branches:
3 | ignore:
4 | - gh-pages
5 |
--------------------------------------------------------------------------------
/types/typings.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-router",
3 | "main": "index.d.ts"
4 | }
5 |
--------------------------------------------------------------------------------
/src/util/dom.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | export const inBrowser = typeof window !== 'undefined'
4 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["es2015-loose", "flow-vue"],
3 | "plugins": ["syntax-dynamic-import"]
4 | }
5 |
--------------------------------------------------------------------------------
/examples/auth-flow/components/About.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
About
4 |
5 |
6 |
--------------------------------------------------------------------------------
/examples/auth-flow/components/Dashboard.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Dashboard
4 |
Yay you made it!
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/lazy-loading/Baz.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Baz
4 |
I'm loaded in the same chunk with Bar.
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
5 |
--------------------------------------------------------------------------------
/.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/_book
11 |
--------------------------------------------------------------------------------
/examples/lazy-loading/Foo.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
This is Foo!
4 |
I am lazy-loaded. (check out the Networks tab in Chrome devtools)
5 |
6 |
7 |
--------------------------------------------------------------------------------
/docs/LANGS.md:
--------------------------------------------------------------------------------
1 | * [2.0 - English](en/)
2 | * [2.0 - Japanese](ja/)
3 | * [2.0 - 中文](zh-cn/)
4 | * [2.0 - German](de/)
5 | * [2.0 - Русский](ru/)
6 | * [2.0 - 한국어(Korean)](kr/)
7 | * [0.7 Docs](old/)
8 |
--------------------------------------------------------------------------------
/test/unit/jasmine.json:
--------------------------------------------------------------------------------
1 | {
2 | "spec_dir": "test/unit/specs",
3 | "spec_files": [
4 | "*.spec.js"
5 | ],
6 | "helpers": [
7 | "../../../node_modules/babel-register/lib/node.js"
8 | ]
9 | }
10 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "babel-eslint",
4 | "extends": "vue",
5 | "plugins": ["flow-vars"],
6 | "rules": {
7 | "flow-vars/define-flow-type": 1,
8 | "flow-vars/use-flow-type": 1
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/examples/basic/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/redirect/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/auth-flow/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/hash-mode/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/named-views/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/route-alias/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/route-props/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/data-fetching/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/lazy-loading/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/named-routes/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/navigation-guards/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | ← Examples index
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/route-props/Hello.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Hello {{name}}
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/lazy-loading/Bar.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
{{ msg }}
4 |
I am lazy-loaded. (check out the Networks tab in Chrome devtools)
5 |
6 |
7 |
8 |
9 |
16 |
--------------------------------------------------------------------------------
/src/util/warn.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | export function assert (condition: any, message: string) {
4 | if (!condition) {
5 | throw new Error(`[vue-router] ${message}`)
6 | }
7 | }
8 |
9 | export function warn (condition: any, message: string) {
10 | if (!condition) {
11 | typeof console !== 'undefined' && console.warn(`[vue-router] ${message}`)
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/examples/scroll-behavior/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 | ← Examples index
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/types/test/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "noImplicitAny": true,
6 | "strictNullChecks": true,
7 | "noEmit": true,
8 | "lib": [
9 | "es5",
10 | "dom",
11 | "es2015.promise",
12 | "es2015.core"
13 | ]
14 | },
15 | "include": [
16 | "*.ts",
17 | "../*.d.ts"
18 | ]
19 | }
20 |
--------------------------------------------------------------------------------
/examples/active-links/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 | ← Examples index
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-router",
3 | "main": "dist/vue-router.js",
4 | "description": "official router for Vue.js",
5 | "authors": "Evan You",
6 | "license": "MIT",
7 | "ignore": [
8 | "examples",
9 | "test",
10 | "docs",
11 | ".gitignore",
12 | ".eslintrc",
13 | ".babelrc",
14 | "*.json",
15 | "*.md",
16 | "*.yml",
17 | "*.lock"
18 | ]
19 | }
20 |
--------------------------------------------------------------------------------
/src/util/async.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | export function runQueue (queue: Array, fn: Function, cb: Function) {
4 | const step = index => {
5 | if (index >= queue.length) {
6 | cb()
7 | } else {
8 | if (queue[index]) {
9 | fn(queue[index], () => {
10 | step(index + 1)
11 | })
12 | } else {
13 | step(index + 1)
14 | }
15 | }
16 | }
17 | step(0)
18 | }
19 |
--------------------------------------------------------------------------------
/examples/nested-routes/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
13 | ← Examples index
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/docs/zh-cn/api/component-injections.md:
--------------------------------------------------------------------------------
1 | # 对组件注入
2 |
3 | ### 注入的属性
4 |
5 |
6 | 通过在 Vue 根实例的 `router` 配置传入 router 实例,下面这些属性成员会被注入到每个子组件。
7 |
8 | - #### $router
9 |
10 | router 实例.
11 |
12 | - #### $route
13 |
14 | 当前激活的 [路由信息对象](route-object.md)。这个属性是只读的,里面的属性是 immutable(不可变) 的,不过你可以 watch(监测变化) 它。
15 |
16 | ### 允许的额外配置
17 |
18 | - **beforeRouteEnter**
19 | - **beforeRouteLeave**
20 |
21 | 查看 [组件级导航钩子](../advanced/navigation-guards.md#incomponent-guards).
22 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/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 | - **beforeRouteLeave**
19 |
20 | [컴포넌트 내부 가드](../advanced/navigation-guards.md#incomponent-guards)를 확인하세요.
21 |
--------------------------------------------------------------------------------
/docs/ja/api/component-injections.md:
--------------------------------------------------------------------------------
1 | # コンポーネント注入
2 |
3 | ### 注入されるプロパティ
4 |
5 | ルーターインスタンスを root インスタンスに `router` オプションとして渡すことによって、全ての子コンポーネントに以下のプロパティが注入されます。
6 |
7 | - #### $router
8 |
9 | ルーターインスタンス
10 |
11 | - #### $route
12 |
13 | 現在のアクティブな [ルート](route-object.md) 。このプロパティは読み出しのみ可能かつ変更不可ですが、watch は可能です。
14 |
15 | ### Enabled Options
16 |
17 | - **beforeRouteEnter**
18 | - **beforeRouteLeave**
19 |
20 | [コンポーネント内ガード](../advanced/navigation-guards.md#incomponent-guards) をご参照ください。
21 |
--------------------------------------------------------------------------------
/test/unit/specs/async.spec.js:
--------------------------------------------------------------------------------
1 | import { runQueue } from '../../../src/util/async'
2 |
3 | describe('Async utils', () => {
4 | describe('runQueue', () => {
5 | it('should work', done => {
6 | const calls = []
7 | const queue = [1, 2, 3, 4, 5].map(i => next => {
8 | calls.push(i)
9 | setTimeout(done, 0)
10 | })
11 | runQueue(queue, (fn, next) => fn(next), () => {
12 | expect(calls).toEqual([1, 2, 3, 4, 5])
13 | done()
14 | })
15 | })
16 | })
17 | })
18 |
--------------------------------------------------------------------------------
/docs/book.json:
--------------------------------------------------------------------------------
1 | {
2 | "gitbook": ">3.0.0",
3 | "plugins": ["edit-link", "theme-vuejs@git+https://github.com/pearofducks/gitbook-plugin-theme-vuejs.git", "-fontsettings", "github"],
4 | "pluginsConfig": {
5 | "edit-link": {
6 | "base": "https://github.com/vuejs/vue-router/edit/dev/docs",
7 | "label": "Edit This Page"
8 | },
9 | "github": {
10 | "url": "https://github.com/vuejs/vue-router/"
11 | }
12 | },
13 | "links": {
14 | "sharing": {
15 | "facebook": false,
16 | "twitter": false
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/types/vue.d.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Augment the typings of Vue.js
3 | */
4 |
5 | import Vue = require("vue");
6 | import VueRouter = require("./index");
7 | import { Route, RawLocation, NavigationGuard } from "./index";
8 |
9 | declare module "vue/types/vue" {
10 | interface Vue {
11 | $router: VueRouter;
12 | $route: Route;
13 | }
14 | }
15 |
16 | declare module "vue/types/options" {
17 | interface ComponentOptions {
18 | router?: VueRouter;
19 | beforeRouteEnter?: NavigationGuard;
20 | beforeRouteLeave?: NavigationGuard;
21 | beforeRouteUpdate?: NavigationGuard;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/docs/en/api/component-injections.md:
--------------------------------------------------------------------------------
1 | # Component Injections
2 |
3 | ### Injected Properties
4 |
5 | These properties are injected into every child component by passing the router instance to the root instance as the `router` option.
6 |
7 | - #### $router
8 |
9 | The router instance.
10 |
11 | - #### $route
12 |
13 | The current active [Route](route-object.md). This property is read-only and its properties are immutable, but it can be watched.
14 |
15 | ### Enabled Options
16 |
17 | - **beforeRouteEnter**
18 | - **beforeRouteUpdate** (added in 2.2)
19 | - **beforeRouteLeave**
20 |
21 | See [In Component Guards](../advanced/navigation-guards.md#incomponent-guards).
22 |
--------------------------------------------------------------------------------
/docs/zh-cn/api/router-view.md:
--------------------------------------------------------------------------------
1 | # ``
2 |
3 | `` 组件是一个 functional 组件,渲染路径匹配到的视图组件。`` 渲染的组件还可以内嵌自己的 ``,根据嵌套路径,渲染嵌套组件。
4 |
5 | ### 属性
6 |
7 | - **name**
8 |
9 | - 类型: `string`
10 |
11 | - 默认值: `"default"`
12 |
13 | 如果 ``设置了名称,则会渲染对应的路由配置中 `components` 下的相应组件。查看 [命名视图](../essentials/named-views.md) 中的例子。
14 |
15 | ### 行为表现
16 |
17 | 其他属性(非 router-view 使用的属性)都直接传给渲染的组件,
18 | 很多时候,每个路由的数据都是包含在路由参数中。
19 |
20 | 因为它也是个组件,所以可以配合 `` 和 `` 使用。如果两个结合一起用,要确保在内层使用 ``:
21 |
22 | ``` html
23 |
24 |
25 |
26 |
27 |
28 | ```
29 |
--------------------------------------------------------------------------------
/docs/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/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 | - **beforeRouteLeave**
19 |
20 | См. [раздел документации о сторожевых хуках](../advanced/navigation-guards.md#incomponent-guards).
21 |
--------------------------------------------------------------------------------
/docs/zh-cn/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` 属性传一个对象:
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/next/examples/named-routes/app.js).
32 |
--------------------------------------------------------------------------------
/docs/zh-cn/essentials/named-views.md:
--------------------------------------------------------------------------------
1 | # 命名视图
2 |
3 | 有时候想同时(同级)展示多个视图,而不是嵌套展示,例如创建一个布局,有 `sidebar`(侧导航) 和 `main`(主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 `router-view` 没有设置名字,那么默认为 `default`。
4 |
5 |
6 | ``` html
7 |
8 |
9 |
10 | ```
11 |
12 | 一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 `components` 配置(带上 s):
13 |
14 | ``` js
15 | const router = new VueRouter({
16 | routes: [
17 | {
18 | path: '/',
19 | components: {
20 | default: Foo,
21 | a: Bar,
22 | b: Baz
23 | }
24 | }
25 | ]
26 | })
27 | ```
28 |
29 | 以上案例相关的可运行代码,在
30 | [这里](https://jsfiddle.net/posva/6du90epg/).
31 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/test/unit/specs/discrete-components.spec.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import VueRouter from '../../../src/index'
3 |
4 | describe('[Vue Instance].$route bindings', () => {
5 | describe('boundToSingleVueInstance', () => {
6 | it('updates $route on all instances', () => {
7 | const router = new VueRouter({
8 | routes: [
9 | { path: '/', component: { name: 'foo' }},
10 | { path: '/bar', component: { name: 'bar' }}
11 | ]
12 | })
13 | const app1 = new Vue({ router })
14 | const app2 = new Vue({ router })
15 | expect(app1.$route.path).toBe('/')
16 | expect(app2.$route.path).toBe('/')
17 | router.push('/bar')
18 | expect(app1.$route.path).toBe('/bar')
19 | expect(app2.$route.path).toBe('/bar')
20 | })
21 | })
22 | })
23 |
--------------------------------------------------------------------------------
/docs/ja/api/router-view.md:
--------------------------------------------------------------------------------
1 | # ``
2 |
3 | `` コンポーネントは与えられたパスに対してマッチしたコンポーネントをレンダリングする関数型コンポーネントです。`` の中でレンダリングされるコンポーネント自身もまた、ネストされたパスに対してコンポーネントをレンダリングするための `` を持つことができます。
4 |
5 | ### プロパティ
6 |
7 | - **name**
8 |
9 | - 型: `string`
10 |
11 | - デフォルト: `"default"`
12 |
13 | `` が名前を持つ時、マッチしたルートレコードの `components` オプション内で対応する名前のコンポーネントをレンダリングします。例は [名前付きビュー](../essentials/named-views.md) をご参照ください。
14 |
15 | ### 振る舞い
16 |
17 | name ではないプロパティもレンダリングされるコンポーネントに渡されますが、ほとんどの場合ルート単位のデータはルートのパラメーターに含まれています。
18 |
19 | これは普通のコンポーネントなので、 `` と `` と共に動作します。両方を同時に使用する場合は `` を内側にするようにしてください。
20 |
21 | ``` html
22 |
23 |
24 |
25 |
26 |
27 | ```
28 |
--------------------------------------------------------------------------------
/types/index.d.ts:
--------------------------------------------------------------------------------
1 | import "./vue";
2 | import * as R from "./router";
3 |
4 | // `VueRouter` in `export = VueRouter` must be a namespace
5 | // All available types are exported via this namespace
6 | declare namespace VueRouter {
7 | export type RouterMode = R.RouterMode;
8 | export type RawLocation = R.RawLocation;
9 | export type RedirectOption = R.RedirectOption;
10 | export type RouterOptions = R.RouterOptions;
11 | export type RouteConfig = R.RouteConfig;
12 | export type RouteRecord = R.RouteRecord;
13 | export type Location = R.Location;
14 | export type Route = R.Route;
15 | export type NavigationGuard = R.NavigationGuard;
16 | }
17 |
18 | // TS cannot merge imported class with namespace, declare a subclass to bypass
19 | declare class VueRouter extends R.VueRouter {}
20 |
21 | export = VueRouter;
22 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/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/ja/essentials/named-routes.md:
--------------------------------------------------------------------------------
1 | # 名前付きルート
2 |
3 | しばしば、名前を使ってルートを特定できるとより便利です。特にルートにリンクするときやナビゲーションを実行するときなどです。Router インスタンスを作成するときに `routes` オプションの中でルートに名前を付けることができます。
4 |
5 | ``` js
6 | const router = new VueRouter({
7 | routes: [
8 | {
9 | path: '/user/:id',
10 | name: 'user',
11 | component: User
12 | }
13 | ]
14 | })
15 | ```
16 |
17 | 名前を付けたルートにリンクするには、 `router-link` コンポーネントの `to` プロパティにオブジェクトを渡します。
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 |
--------------------------------------------------------------------------------
/examples/transitions/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
25 | ← Examples index
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/docs/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/ja/essentials/named-views.md:
--------------------------------------------------------------------------------
1 | # 名前付きビュー
2 |
3 | しばしば、ネストをさせずに同時に複数の view を表示する必要があるでしょう。例えば、`sidebar` view と `main` view を使ったレイアウトを作成する時です。そんな時に名前付きビューは便利です。あなたの view に 1 つのアウトレットを持つのではなく、複数のそれぞれが名前付きの view を持つことができます。名前を持たない `router-view` はその名前として `default` が付与されます。
4 |
5 | ``` html
6 |
7 |
8 |
9 | ```
10 |
11 | 1 つの view は 1 つのコンポーネントを使ってレンダリングされます。したがって、同じルートに対する複数の view には複数のコンポーネントが必須になります。この `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 | この例の動作しているデモは
29 | [こちら](https://jsfiddle.net/posva/6du90epg/) です。
30 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/test/e2e/specs/route-props.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'route-props': function (browser) {
3 | browser
4 | .url('http://localhost:8080/route-props/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 4)
7 |
8 | .assert.urlEquals('http://localhost:8080/route-props/')
9 | .assert.containsText('.hello', 'Hello Vue!')
10 |
11 | .click('li:nth-child(2) a')
12 | .assert.urlEquals('http://localhost:8080/route-props/hello/you')
13 | .assert.containsText('.hello', 'Hello you')
14 |
15 | .click('li:nth-child(3) a')
16 | .assert.urlEquals('http://localhost:8080/route-props/static')
17 | .assert.containsText('.hello', 'Hello world')
18 |
19 | .click('li:nth-child(4) a')
20 | .assert.urlEquals('http://localhost:8080/route-props/dynamic/1')
21 | .assert.containsText('.hello', 'Hello ' + ((new Date()).getFullYear() + 1)+ '!')
22 |
23 | .end()
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/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(webpackDevMiddleware(webpack(WebpackConfig), {
10 | publicPath: '/__build__/',
11 | stats: {
12 | colors: true,
13 | chunks: false
14 | }
15 | }))
16 |
17 | const fs = require('fs')
18 | const path = require('path')
19 |
20 | fs.readdirSync(__dirname).forEach(file => {
21 | if (fs.statSync(path.join(__dirname, file)).isDirectory()) {
22 | app.use(rewrite('/' + file + '/*', '/' + file + '/index.html'))
23 | }
24 | })
25 |
26 | app.use(express.static(__dirname))
27 |
28 | const port = process.env.PORT || 8080
29 | module.exports = app.listen(port, () => {
30 | console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`)
31 | })
32 |
--------------------------------------------------------------------------------
/docs/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 | Чтобы сослаться на именованный маршрут, используйте объектную запись:
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 |
--------------------------------------------------------------------------------
/test/e2e/runner.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var spawn = require('cross-spawn')
3 | var args = process.argv.slice(2)
4 |
5 | var server = args.indexOf('--dev') > -1
6 | ? null
7 | : require('../../examples/server')
8 |
9 | if (args.indexOf('--config') === -1) {
10 | args = args.concat(['--config', 'test/e2e/nightwatch.config.js'])
11 | }
12 | if (args.indexOf('--env') === -1) {
13 | args = args.concat(['--env', process.env.CIRCLECI ? 'phantomjs' : 'chrome'])
14 | }
15 | var i = args.indexOf('--test')
16 | if (i > -1) {
17 | args[i + 1] = 'test/e2e/specs/' + args[i + 1].replace(/\.js$/, '') + '.js'
18 | }
19 | if (args.indexOf('phantomjs') > -1) {
20 | process.env.PHANTOMJS = true
21 | }
22 |
23 | var runner = spawn('./node_modules/.bin/nightwatch', args, {
24 | stdio: 'inherit'
25 | })
26 |
27 | runner.on('exit', function (code) {
28 | server && server.close()
29 | process.exit(code)
30 | })
31 |
32 | runner.on('error', function (err) {
33 | server && server.close()
34 | throw err
35 | })
36 |
--------------------------------------------------------------------------------
/test/unit/specs/query.spec.js:
--------------------------------------------------------------------------------
1 | import { resolveQuery, stringifyQuery } from '../../../src/util/query'
2 |
3 | describe('Query utils', () => {
4 | describe('resolveQuery', () => {
5 | it('should work', () => {
6 | const query = resolveQuery('foo=bar&foo=k', { baz: 'qux' })
7 | expect(JSON.stringify(query)).toBe(JSON.stringify({
8 | foo: ['bar', 'k'],
9 | baz: 'qux'
10 | }))
11 | })
12 | })
13 |
14 | describe('stringifyQuery', () => {
15 | it('should work', () => {
16 | expect(stringifyQuery({
17 | foo: 'bar',
18 | baz: 'qux',
19 | arr: [1, 2]
20 | })).toBe('?foo=bar&baz=qux&arr=1&arr=2')
21 | })
22 |
23 | it('should escape reserved chars', () => {
24 | expect(stringifyQuery({
25 | a: '*()!'
26 | })).toBe('?a=%2a%28%29%21')
27 | })
28 |
29 | it('should preserve commas', () => {
30 | expect(stringifyQuery({
31 | list: '1,2,3'
32 | })).toBe('?list=1,2,3')
33 | })
34 | })
35 | })
36 |
--------------------------------------------------------------------------------
/docs/en/essentials/named-routes.md:
--------------------------------------------------------------------------------
1 | # Named Routes
2 |
3 | Sometimes it is more convenient to identify a route with a name, especially when linking to a route or performing navigations. You can give a route a name in the `routes` options while creating the Router instance:
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 link to a named route, you can pass an object to the `router-link`
18 | component's `to` prop:
19 |
20 | ``` html
21 | User
22 | ```
23 |
24 | This is the exact same object used programatically with `router.push()`:
25 |
26 | ``` js
27 | router.push({ name: 'user', params: { userId: 123 }})
28 | ```
29 |
30 | In both cases, the router will navigate to the path `/user/123`.
31 |
32 | Full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js).
33 |
--------------------------------------------------------------------------------
/src/install.js:
--------------------------------------------------------------------------------
1 | import View from './components/view'
2 | import Link from './components/link'
3 |
4 | export let _Vue
5 |
6 | export function install (Vue) {
7 | if (install.installed) return
8 | install.installed = true
9 |
10 | _Vue = Vue
11 |
12 | Object.defineProperty(Vue.prototype, '$router', {
13 | get () { return this.$root._router }
14 | })
15 |
16 | Object.defineProperty(Vue.prototype, '$route', {
17 | get () { return this.$root._route }
18 | })
19 |
20 | Vue.mixin({
21 | beforeCreate () {
22 | if (this.$options.router) {
23 | this._router = this.$options.router
24 | this._router.init(this)
25 | Vue.util.defineReactive(this, '_route', this._router.history.current)
26 | }
27 | }
28 | })
29 |
30 | Vue.component('router-view', View)
31 | Vue.component('router-link', Link)
32 |
33 | const strats = Vue.config.optionMergeStrategies
34 | // use the same hook merging strategy for route hooks
35 | strats.beforeRouteEnter = strats.beforeRouteLeave = strats.created
36 | }
37 |
--------------------------------------------------------------------------------
/examples/auth-flow/components/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Auth Flow
4 |
5 |
6 | Log out
7 | Log in
8 |
9 |
10 | About
11 |
12 |
13 | Dashboard
14 | (authenticated)
15 |
16 |
17 |
18 |
19 |
20 |
21 | You are logged {{ loggedIn ? 'in' : 'out' }}
22 |
23 |
24 |
25 |
26 |
42 |
--------------------------------------------------------------------------------
/docs/de/essentials/named-routes.md:
--------------------------------------------------------------------------------
1 | # Benannte Routes
2 |
3 | Manchmal ist es einfacher einer 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 | Dass 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/en/api/router-view.md:
--------------------------------------------------------------------------------
1 | # ``
2 |
3 | The `` component is a functional component that renders the matched component for the given path. Components rendered in `` can also contain its own ``, which will render components for nested paths.
4 |
5 | ### Props
6 |
7 | - **name**
8 |
9 | - type: `string`
10 |
11 | - default: `"default"`
12 |
13 | When a `` has a name, it will render the component with the corresponding name in the matched route record's `components` option. See [Named Views](../essentials/named-views.md) for an example.
14 |
15 | ### Behavior
16 |
17 | Any non-name props will be passed along to the rendered component, however most of the time the per-route data is contained in the route's params.
18 |
19 | Since it's just a component, it works with `` and ``. When using the both together, make sure to use `` inside:
20 |
21 | ``` html
22 |
23 |
24 |
25 |
26 |
27 | ```
28 |
--------------------------------------------------------------------------------
/docs/zh-cn/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` 这样指定 版本号 或者 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 | ### 构建开发版
36 |
37 | 如果你想使用最新的开发版,就得从 GitHub 上直接 clone,然后自己 build 一个 `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 |
--------------------------------------------------------------------------------
/test/e2e/specs/data-fetching.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'data fetching': function (browser) {
3 | browser
4 | .url('http://localhost:8080/data-fetching/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 4)
7 | .assert.containsText('.view', 'home')
8 |
9 | .click('li:nth-child(2) a')
10 | .waitForElementNotPresent('.loading', 500)
11 | .assert.containsText('.post h2', 'sunt aut facere')
12 | .assert.containsText('.post p', 'quia et suscipit')
13 |
14 | .click('li:nth-child(3) a')
15 | .waitForElementNotPresent('.loading', 500)
16 | .assert.containsText('.post h2', 'qui est esse')
17 | .assert.containsText('.post p', 'est rerum tempore')
18 |
19 | .click('li:nth-child(4) a')
20 | .waitForElementNotPresent('.loading', 500)
21 | .assert.elementNotPresent('.content')
22 | .assert.containsText('.error', 'Post not found')
23 |
24 | .click('li:nth-child(1) a')
25 | .assert.elementNotPresent('.post')
26 | .assert.containsText('.view', 'home')
27 | .end()
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/docs/en/essentials/named-views.md:
--------------------------------------------------------------------------------
1 | # Named Views
2 |
3 | Sometimes you need to display multiple views at the same time instead of nesting them, e.g. creating a layout with a `sidebar` view and a `main` view. This is where named views came in handy. Instead of having one single outlet in your view, you can have multiple and give each of them a name. A `router-view` without a name will be given `default` as its name.
4 |
5 | ``` html
6 |
7 |
8 |
9 | ```
10 |
11 | A view is rendered by using a component, therefore multiple views require multiple components for the same route. Make sure to use the `components` (with
12 | an s) option:
13 |
14 | ``` js
15 | const router = new VueRouter({
16 | routes: [
17 | {
18 | path: '/',
19 | components: {
20 | default: Foo,
21 | a: Bar,
22 | b: Baz
23 | }
24 | }
25 | ]
26 | })
27 | ```
28 |
29 | A working demo of this example can be found
30 | [here](https://jsfiddle.net/posva/6du90epg/).
31 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2013-2016 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 |
--------------------------------------------------------------------------------
/examples/auth-flow/components/Login.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Login
4 |
5 | You need to login first.
6 |
7 |
13 |
14 |
15 |
16 |
40 |
41 |
46 |
--------------------------------------------------------------------------------
/docs/ja/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 | グローバルな 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 |
--------------------------------------------------------------------------------
/test/e2e/specs/lazy-loading.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'lazy loading': function (browser) {
3 | browser
4 | .url('http://localhost:8080/lazy-loading/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 4)
7 | .assert.containsText('.view', 'home')
8 |
9 | .click('li:nth-child(2) a')
10 | .assert.containsText('.view', 'This is Foo!')
11 |
12 | .click('li:nth-child(3) a')
13 | .assert.containsText('.view', 'This is Bar!')
14 |
15 | .click('li:nth-child(1) a')
16 | .assert.containsText('.view', 'home')
17 |
18 | .click('li:nth-child(4) a')
19 | .assert.containsText('.view', 'This is Bar!')
20 | .assert.containsText('.view h3', 'Baz')
21 |
22 | // test initial visit
23 | .url('http://localhost:8080/lazy-loading/foo')
24 | .waitForElementVisible('#app', 1000)
25 | .assert.containsText('.view', 'This is Foo!')
26 |
27 | .url('http://localhost:8080/lazy-loading/bar/baz')
28 | .waitForElementVisible('#app', 1000)
29 | .assert.containsText('.view', 'This is Bar!')
30 | .assert.containsText('.view h3', 'Baz')
31 | .end()
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/docs/zh-cn/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # vue-router 2
2 |
3 | > 注意: vue-router@2.x 只适用于 Vue 2.x 版本。1.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 | - [HTML5 History 模式](essentials/history-mode.md)
17 | - 进阶
18 | - [导航钩子](advanced/navigation-guards.md)
19 | - [路由元信息](advanced/meta.md)
20 | - [过渡动效](advanced/transitions.md)
21 | - [数据获取](advanced/data-fetching.md)
22 | - [滚动行为](advanced/scroll-behavior.md)
23 | - [懒加载](advanced/lazy-loading.md)
24 | - API 文档
25 | - [router-link](api/router-link.md)
26 | - [router-view](api/router-view.md)
27 | - [路由信息对象](api/route-object.md)
28 | - [Router 构造配置](api/options.md)
29 | - [Router 实例](api/router-instance.md)
30 | - [对组件注入](api/component-injections.md)
31 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/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/ru/essentials/named-views.md:
--------------------------------------------------------------------------------
1 | # Именованные представления
2 |
3 | Иногда необходимо отобразить сразу несколько компонентов, не вкладывая их один в другой — например, при создании разметки с боковой панелью и основным контентом. В этой ситуации может быть удобно использовать именованные представления. Вместо указания единственного ``, можно использовать несколько, присвоив каждому собственное имя. Безымянный `router-view` автоматически получает имя `default`.
4 |
5 | ``` html
6 |
7 |
8 |
9 | ```
10 |
11 | При использовании нескольких представлений, вместо единственного компонента при описании пути необходимо указывать объект. Удостоверьтесь, что используете окончание множественного числа (`s`) в ключе `components`:
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 |
--------------------------------------------------------------------------------
/src/util/params.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import Regexp from 'path-to-regexp'
4 | import { warn } from './warn'
5 |
6 | const regexpCache: {
7 | [key: string]: {
8 | keys: Array{ name: string }>,
9 | regexp: RegExp
10 | }
11 | } = Object.create(null)
12 |
13 | export function getRouteRegex (path: string): Object {
14 | const hit = regexpCache[path]
15 | let keys, regexp
16 |
17 | if (hit) {
18 | keys = hit.keys
19 | regexp = hit.regexp
20 | } else {
21 | keys = []
22 | regexp = Regexp(path, keys)
23 | regexpCache[path] = { keys, regexp }
24 | }
25 |
26 | return { keys, regexp }
27 | }
28 |
29 | const regexpCompileCache: {
30 | [key: string]: Function
31 | } = Object.create(null)
32 |
33 | export function fillParams (
34 | path: string,
35 | params: ?Object,
36 | routeMsg: string
37 | ): string {
38 | try {
39 | const filler =
40 | regexpCompileCache[path] ||
41 | (regexpCompileCache[path] = Regexp.compile(path))
42 | return filler(params || {}, { pretty: true })
43 | } catch (e) {
44 | if (process.env.NODE_ENV !== 'production') {
45 | warn(false, `missing param for ${routeMsg}: ${e.message}`)
46 | }
47 | return ''
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/test/unit/specs/node.spec.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import VueRouter from '../../../src/index'
3 |
4 | Vue.use(VueRouter)
5 |
6 | describe('Usage in Node', () => {
7 | it('should be in abstract mode', () => {
8 | const router = new VueRouter()
9 | expect(router.mode).toBe('abstract')
10 | })
11 |
12 | it('should be able to navigate without app instance', () => {
13 | const router = new VueRouter({
14 | routes: [
15 | { path: '/', component: { name: 'foo' }},
16 | { path: '/bar', component: { name: 'bar' }}
17 | ]
18 | })
19 | router.push('/bar')
20 | expect(router.history.current.path).toBe('/bar')
21 | })
22 |
23 | it('getMatchedComponents', () => {
24 | const Foo = { name: 'foo' }
25 | const Bar = { name: 'bar' }
26 | const Baz = { name: 'baz' }
27 | const router = new VueRouter({
28 | routes: [
29 | { path: '/', component: Foo },
30 | { path: '/bar', component: Bar, children: [
31 | { path: 'baz', component: Baz }
32 | ]}
33 | ]
34 | })
35 | expect(router.getMatchedComponents('/')).toEqual([Foo])
36 | expect(router.getMatchedComponents('/bar/baz')).toEqual([Bar, Baz])
37 | })
38 | })
39 |
--------------------------------------------------------------------------------
/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/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Vue Router Examples
5 |
6 |
7 |
8 | Vue Router Examples
9 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/test/unit/specs/create-matcher.spec.js:
--------------------------------------------------------------------------------
1 | /*eslint-disable no-undef*/
2 | import { createMatcher } from '../../../src/create-matcher'
3 |
4 | const routes = [
5 | { path: '/', name: 'home', component: { name: 'home' } },
6 | { path: '/foo', name: 'foo', component: { name: 'foo' } },
7 | ]
8 |
9 | describe('Creating Matcher', function () {
10 | let match
11 |
12 | beforeAll(function () {
13 | spyOn(console, 'warn')
14 | match = createMatcher(routes).match
15 | })
16 |
17 | beforeEach(function () {
18 | console.warn.calls.reset()
19 | process.env.NODE_ENV = 'production'
20 | })
21 |
22 | it('in development, has logged a warning if a named route does not exist', function () {
23 | process.env.NODE_ENV = 'development'
24 | expect(() => {
25 | match({ name: 'bar' }, routes[0]);
26 | }).toThrow(new TypeError('Cannot read property \'path\' of undefined'));
27 | expect(console.warn).toHaveBeenCalled()
28 | expect(console.warn.calls.argsFor(0)[0]).toMatch('Route with name \'bar\' does not exist');
29 | })
30 |
31 | it('in production, it has not logged this warning', function () {
32 | match({ name: 'foo' }, routes[0]);
33 | expect(console.warn).not.toHaveBeenCalled()
34 | })
35 | })
36 |
--------------------------------------------------------------------------------
/docs/zh-cn/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 对象)的 `$route.matched` 数组。因此,我们需要遍历 `$route.matched` 来检查路由记录中的 `meta` 字段。
31 |
32 | 下面例子展示在全局导航钩子中检查 meta 字段:
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/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/zh-cn/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 | 其它高级用法,请参考 [例子](https://github.com/vuejs/vue-router/blob/next/examples/redirect/app.js).
39 |
40 | ### 别名
41 |
42 | 『重定向』的意思是,当用户访问 `/a`时,URL 将会被替换成 `/b`,然后匹配路由为 `/b`,那么『别名』又是什么呢?
43 |
44 | **`/a` 的别名是 `/b`,意味着,当用户访问 `/b` 时,URL 会保持为 `/b`,但是路由匹配则为 `/a`,就像用户访问 `/a` 一样。**
45 |
46 | 上面对应的路由配置为:
47 |
48 | ``` js
49 | const router = new VueRouter({
50 | routes: [
51 | { path: '/a', component: A, alias: '/b' }
52 | ]
53 | })
54 | ```
55 |
56 | 『别名』的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构。
57 |
58 | 更多高级用法,请查看 [例子](https://github.com/vuejs/vue-router/blob/next/examples/route-alias/app.js).
59 |
--------------------------------------------------------------------------------
/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 | document.querySelectorAll('.app').forEach((node) => {
34 | new BaseVue({
35 | el: node
36 | })
37 | })
38 |
--------------------------------------------------------------------------------
/docs/kr/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # vue-router 2
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 | - [router-link](api/router-link.md)
27 | - [router-view](api/router-view.md)
28 | - [라우트 객체](api/route-object.md)
29 | - [라우터 생성자 옵션](api/options.md)
30 | - [라우터 인스턴스](api/router-instance.md)
31 | - [컴포넌트 주입](api/component-injections.md)
32 |
--------------------------------------------------------------------------------
/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 |
43 |
44 |
45 |
46 |
47 | `
48 | }).$mount('#app')
49 |
--------------------------------------------------------------------------------
/docs/ja/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 | ではどのように `meta` フィールドにアクセスしましょう?
25 |
26 | まず、 `routes` 設定の中の各ルートオブジェクトは**ルートレコード**と呼ばれます。ルートレコードはネストされているかもしれません。したがって、ルートがマッチした時に、潜在的には 1 つ以上のルートレコードがマッチされる可能性があります。
27 |
28 | 例えば上記のルート設定で、 `/foo/bar` という URL は親のルートレコードにも子のルートレコードにもマッチします。
29 |
30 | ルートにマッチした全てのルートレコードは `$route.matched` 配列として `$route` オブジェクト上で (また、ナビゲーションガード上のルートオブジェクトでも) アクセス可能になります。
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 | ```
53 |
--------------------------------------------------------------------------------
/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 | ]
23 | })
24 |
25 | new Vue({
26 | router,
27 | template: `
28 |
29 |
Route props
30 |
31 | /
32 | /hello/you
33 | /static
34 | /dynamic/1
35 |
36 |
37 |
38 | `
39 | }).$mount('#app')
40 |
--------------------------------------------------------------------------------
/docs/ja/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # vue-router 2
2 |
3 | > 注意: vue-router@2.x は Vue 2.x のみで動作します。[0.7 のドキュメントをお探しですか?](https://github.com/vuejs/vue-router/tree/1.0/docs/ja)
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 | - [router-link](api/router-link.md)
27 | - [router-view](api/router-view.md)
28 | - [ルートオブジェクト](api/route-object.md)
29 | - [ルーターコンストラクタオプション](api/options.md)
30 | - [ルーターインスタンス](api/router-instance.md)
31 | - [コンポーネント注入](api/component-injections.md)
32 |
--------------------------------------------------------------------------------
/docs/en/installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | ### Direct Download / 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) provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like `https://unpkg.com/vue-router@2.0.0/dist/vue-router.js`.
9 |
10 |
11 | Include `vue-router` after Vue and it will install itself automatically:
12 |
13 | ``` html
14 |
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 | ### Dev Build
36 |
37 | You will have to clone directly from GitHub and build `vue-router` yourself if
38 | you want to use the latest dev build.
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/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/zh-cn/advanced/transitions.md:
--------------------------------------------------------------------------------
1 | # 过渡动效
2 |
3 | `` 是基本的动态组件,所以我们可以用 `` 组件给它添加一些过渡效果:
4 |
5 |
6 | ``` html
7 |
8 |
9 |
10 | ```
11 |
12 | [`` 的所有功能](http://vuejs.org/guide/transitions.html) 在这里同样适用。
13 |
14 | ### 单个路由的过渡
15 |
16 | 上面的用法会给所有路由设置一样的过渡效果,如果你想让每个路由组件有各自的过渡效果,可以在各路由组件内使用 `` 并设置不同的 name。
17 |
18 | ``` js
19 | const Foo = {
20 | template: `
21 |
22 | ...
23 |
24 | `
25 | }
26 |
27 | const Bar = {
28 | template: `
29 |
30 | ...
31 |
32 | `
33 | }
34 | ```
35 |
36 | ### 基于路由的动态过渡
37 |
38 | 还可以基于当前路由与目标路由的变化关系,动态设置过渡效果:
39 |
40 | ``` html
41 |
42 |
43 |
44 |
45 | ```
46 |
47 | ``` js
48 | // 接着在父组件内
49 | // watch $route 决定使用哪种过渡
50 | watch: {
51 | '$route' (to, from) {
52 | const toDepth = to.path.split('/').length
53 | const fromDepth = from.path.split('/').length
54 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
55 | }
56 | }
57 | ```
58 |
59 | 查看完整例子 [这里](https://github.com/vuejs/vue-router/blob/next/examples/transitions/app.js).
60 |
--------------------------------------------------------------------------------
/docs/zh-cn/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # Router 实例
2 |
3 | ### 属性
4 |
5 | #### router.app
6 |
7 | - 类型: `Vue instance`
8 |
9 | 配置了 `router` 的 Vue 根实例。
10 |
11 | #### router.mode
12 |
13 | - 类型: `string`
14 |
15 | 路由使用的 [模式](options.md#mode)。
16 |
17 | #### router.currentRoute
18 |
19 | - 类型: `Route`
20 |
21 | 当前路由对应的 [路由信息对象](route-object.md).
22 |
23 | ### 方法
24 |
25 | - **router.beforeEach(guard)**
26 | - **router.afterEach(hook)**
27 |
28 | 增加全局的导航钩子。参考 [导航钩子](../advanced/navigation-guards.md).
29 |
30 |
31 | - **router.push(location)**
32 | - **router.replace(location)**
33 | - **router.go(n)**
34 | - **router.back()**
35 | - **router.forward()**
36 |
37 | 动态的导航到一个新 url。参考 [编程式导航](../essentials/navigation.md).
38 |
39 | - **router.getMatchedComponents(location?)**
40 |
41 | 返回目标位置或是当前路由匹配的组件数组(是数组的定义/构造类,不是实例)。通常在服务端渲染的数据预加载时时候。
42 |
43 | - **router.resolve(location, current?, append?)**
44 |
45 | > 2.1.0+
46 |
47 | 解析目标位置(格式和 `` 的 `to` prop 一样),返回包含如下属性的对象:
48 |
49 | ``` js
50 | {
51 | location: Location;
52 | route: Route;
53 | href: string;
54 | }
55 | ```
56 |
57 | - **router.addRoutes(routes)**
58 |
59 | > 2.2.0+
60 |
61 | 动态添加更多的路由规则。参数必须是一个符合 `routes` 选项要求的数组。
62 |
63 | - **router.onReady(callback)**
64 |
65 | > 2.2.0+
66 |
67 | 添加一个会在第一次路由跳转完成时被调用的回调函数。此方法通常用于等待异步的导航钩子完成,比如在进行服务端渲染的时候。
68 |
--------------------------------------------------------------------------------
/test/e2e/nightwatch.config.js:
--------------------------------------------------------------------------------
1 | // http://nightwatchjs.org/guide#settings-file
2 |
3 | module.exports = {
4 | 'src_folders': ['test/e2e/specs'],
5 | 'output_folder': 'test/e2e/reports',
6 | 'custom_commands_path': ['node_modules/nightwatch-helpers/commands'],
7 | 'custom_assertions_path': ['node_modules/nightwatch-helpers/assertions'],
8 |
9 | 'selenium': {
10 | 'start_process': true,
11 | 'server_path': require('selenium-server').path,
12 | 'host': '127.0.0.1',
13 | 'port': 4444,
14 | 'cli_args': {
15 | 'webdriver.chrome.driver': require('chromedriver').path
16 | }
17 | },
18 |
19 | 'test_settings': {
20 | 'default': {
21 | 'selenium_port': 4444,
22 | 'selenium_host': 'localhost',
23 | 'silent': true,
24 | 'screenshots': {
25 | 'enabled': true,
26 | 'on_failure': true,
27 | 'on_error': false,
28 | 'path': 'test/e2e/screenshots'
29 | }
30 | },
31 |
32 | 'chrome': {
33 | 'desiredCapabilities': {
34 | 'browserName': 'chrome',
35 | 'javascriptEnabled': true,
36 | 'acceptSslCerts': true
37 | }
38 | },
39 |
40 | 'phantomjs': {
41 | 'desiredCapabilities': {
42 | 'browserName': 'phantomjs',
43 | 'javascriptEnabled': true,
44 | 'acceptSslCerts': true
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/examples/hash-mode/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: 'home
' }
11 | const Foo = { template: 'foo
' }
12 | const Bar = { template: 'bar
' }
13 |
14 | // 3. Create the router
15 | const router = new VueRouter({
16 | mode: 'hash',
17 | base: __dirname,
18 | routes: [
19 | { path: '/', component: Home }, // all paths are defined without the hash.
20 | { path: '/foo', component: Foo },
21 | { path: '/bar', component: Bar }
22 | ]
23 | })
24 |
25 | // 4. Create and mount root instance.
26 | // Make sure to inject the router.
27 | // Route components will be rendered inside .
28 | new Vue({
29 | router,
30 | template: `
31 |
32 |
Basic
33 |
34 | /
35 | /foo
36 | /bar
37 | /bar
38 |
39 |
40 |
41 | `
42 | }).$mount('#app')
43 |
--------------------------------------------------------------------------------
/docs/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 selbst automatisch:
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/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 |
--------------------------------------------------------------------------------
/examples/basic/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: 'home
' }
11 | const Foo = { template: 'foo
' }
12 | const Bar = { template: '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 and mount root instance.
26 | // Make sure to inject the router.
27 | // Route components will be rendered inside .
28 | new Vue({
29 | router,
30 | template: `
31 |
32 |
Basic
33 |
34 | /
35 | /foo
36 | /bar
37 |
38 | /bar
39 |
40 |
41 |
42 |
43 | `
44 | }).$mount('#app')
45 |
--------------------------------------------------------------------------------
/test/e2e/specs/hash-mode.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'Hash mode': function (browser) {
3 | browser
4 | .url('http://localhost:8080/hash-mode/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li', 4)
7 | .assert.count('li a', 3)
8 | .assert.attributeContains('li:nth-child(1) a', 'href', '/hash-mode/#/')
9 | .assert.attributeContains('li:nth-child(2) a', 'href', '/hash-mode/#/foo')
10 | .assert.attributeContains('li:nth-child(3) a', 'href', '/hash-mode/#/bar')
11 | .assert.containsText('.view', 'home')
12 |
13 | .click('li:nth-child(2) a')
14 | .assert.urlEquals('http://localhost:8080/hash-mode/#/foo')
15 | .assert.containsText('.view', 'foo')
16 |
17 | .click('li:nth-child(3) a')
18 | .assert.urlEquals('http://localhost:8080/hash-mode/#/bar')
19 | .assert.containsText('.view', 'bar')
20 |
21 | .click('li:nth-child(1) a')
22 | .assert.urlEquals('http://localhost:8080/hash-mode/#/')
23 | .assert.containsText('.view', 'home')
24 |
25 | .click('li:nth-child(4)')
26 | .assert.urlEquals('http://localhost:8080/hash-mode/#/bar')
27 | .assert.containsText('.view', 'bar')
28 |
29 | // check initial visit
30 | .url('http://localhost:8080/hash-mode/#/foo')
31 | .waitForElementVisible('#app', 1000)
32 | .assert.containsText('.view', 'foo')
33 | .end()
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/docs/zh-cn/advanced/scroll-behavior.md:
--------------------------------------------------------------------------------
1 | # 滚动行为
2 |
3 | 使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 `vue-router` 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
4 |
5 | **注意: 这个功能只在 HTML5 history 模式下可用。**
6 |
7 | 当创建一个 Router 实例,你可以提供一个 `scrollBehavior` 方法:
8 |
9 | ``` js
10 | const router = new VueRouter({
11 | routes: [...],
12 | scrollBehavior (to, from, savedPosition) {
13 | // return 期望滚动到哪个的位置
14 | }
15 | })
16 | ```
17 |
18 | `scrollBehavior` 方法接收 `to` 和 `from` 路由对象。第三个参数 `savedPosition` 当且仅当 `popstate` 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。
19 |
20 | 这个方法返回滚动位置的对象信息,长这样:
21 |
22 | - `{ x: number, y: number }`
23 | - `{ selector: string }`
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 | 如果你要模拟『滚动到锚点』的行为:
50 |
51 | ``` js
52 | scrollBehavior (to, from, savedPosition) {
53 | if (to.hash) {
54 | return {
55 | selector: to.hash
56 | }
57 | }
58 | }
59 | ```
60 |
61 | 我们还可以利用 [路由元信息](meta.md) 更细颗粒度地控制滚动。查看完整例子 [这里](https://github.com/vuejs/vue-router/blob/next/examples/scroll-behavior/app.js).
62 |
--------------------------------------------------------------------------------
/docs/ja/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 | また、function を使った動的なリダイレクトもできます。
26 |
27 | ``` js
28 | const router = new VueRouter({
29 | routes: [
30 | { path: '/a', redirect: to => {
31 | // この function は対象のルートを引数として受け取ります
32 | // ここではリダイレクト先の path もしくは location を返します
33 | }}
34 | ]
35 | })
36 | ```
37 |
38 | その他の高度な使い方として、[例](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js) をご参照ください。
39 |
40 | ### エイリアス
41 |
42 | リダイレクトが意図するところは、ユーザーが `/a` に訪問した時に URL を `/b` に置換し、そして `/b` にマッチさせます。ではエイリアスは何でしょうか?
43 |
44 | **`/b` として扱う `/a` のエイリアスは、ユーザーが `/b` に訪問した時に URL は `/b` のままになります。しかし、それはまるでユーザーが `/a` に訪問したかのようにマッチされます。**
45 |
46 | 上記はルートの設定で以下のように表現されます。
47 |
48 | ``` js
49 | const router = new VueRouter({
50 | routes: [
51 | { path: '/a', component: A, alias: '/b' }
52 | ]
53 | })
54 | ```
55 |
56 | 設定のネスト構造による制約とは異なり、エイリアスは UI 構造に任意の URL をマップするための自由さがあります。
57 |
58 | 高度な使い方に関しては、 [例](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js) をご参照ください。
59 |
--------------------------------------------------------------------------------
/docs/zh-cn/advanced/lazy-loading.md:
--------------------------------------------------------------------------------
1 | # 路由懒加载
2 |
3 | 当打包构建应用时,Javascript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
4 |
5 | 结合 Vue 的 [异步组件](http://vuejs.org/guide/components.html#Async-Components) 和 Webpack 的 [code splitting feature](https://webpack.js.org/guides/code-splitting-require/), 轻松实现路由组件的懒加载。
6 |
7 | 我们要做的就是把路由对应的组件定义成异步组件:
8 |
9 | ``` js
10 | const Foo = resolve => {
11 | // require.ensure 是 Webpack 的特殊语法,用来设置 code-split point
12 | // (代码分块)
13 | require.ensure(['./Foo.vue'], () => {
14 | resolve(require('./Foo.vue'))
15 | })
16 | }
17 | ```
18 |
19 | 这里还有另一种代码分块的语法,使用 AMD 风格的 require,于是就更简单了:
20 |
21 | ``` js
22 | const Foo = resolve => require(['./Foo.vue'], resolve)
23 | ```
24 |
25 | 不需要改变任何路由配置,跟之前一样使用 `Foo`:
26 |
27 | ``` js
28 | const router = new VueRouter({
29 | routes: [
30 | { path: '/foo', component: Foo }
31 | ]
32 | })
33 | ```
34 |
35 | ### 把组件按组分块
36 |
37 | 有时候我们想把某个路由下的所有组件都打包在同个异步 chunk 中。只需要 [给 chunk 命名](https://webpack.js.org/guides/code-splitting-require/#chunkname),提供 `require.ensure` 第三个参数作为 chunk 的名称:
38 |
39 | ``` js
40 | const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
41 | const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
42 | const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
43 | ```
44 |
45 | Webpack 将相同 chunk 下的所有异步模块打包到一个异步块里面 —— 这也意味着我们无须明确列出 `require.ensure` 的依赖(传空数组就行)。
46 |
--------------------------------------------------------------------------------
/docs/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 |
--------------------------------------------------------------------------------
/test/e2e/specs/named-views.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'named views': function (browser) {
3 | browser
4 | .url('http://localhost:8080/named-views/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 2)
7 | // assert correct href with base
8 | .assert.attributeContains('li:nth-child(1) a', 'href', '/named-views/')
9 | .assert.attributeContains('li:nth-child(2) a', 'href', '/named-views/other')
10 |
11 | .assert.containsText('.view.one', 'foo')
12 | .assert.containsText('.view.two', 'bar')
13 | .assert.containsText('.view.three', 'baz')
14 |
15 | .click('li:nth-child(2) a')
16 | .assert.urlEquals('http://localhost:8080/named-views/other')
17 | .assert.containsText('.view.one', 'baz')
18 | .assert.containsText('.view.two', 'bar')
19 | .assert.containsText('.view.three', 'foo')
20 |
21 | .click('li:nth-child(1) a')
22 | .assert.urlEquals('http://localhost:8080/named-views/')
23 | .assert.containsText('.view.one', 'foo')
24 | .assert.containsText('.view.two', 'bar')
25 | .assert.containsText('.view.three', 'baz')
26 |
27 | // check initial visit
28 | .url('http://localhost:8080/named-views/other')
29 | .waitForElementVisible('#app', 1000)
30 | .assert.containsText('.view.one', 'baz')
31 | .assert.containsText('.view.two', 'bar')
32 | .assert.containsText('.view.three', 'foo')
33 | .end()
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/docs/ja/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 | // そして親コンポーネントの中で、
48 | // $route を watch して使用するトランジションを決定します
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 | 完全な例は [こちら](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js) をご参照ください。
59 |
--------------------------------------------------------------------------------
/test/e2e/specs/basic.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'basic': function (browser) {
3 | browser
4 | .url('http://localhost:8080/basic/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li', 4)
7 | .assert.count('li a', 4)
8 | // assert correct href with base
9 | .assert.attributeContains('li:nth-child(1) a', 'href', '/basic/')
10 | .assert.attributeContains('li:nth-child(2) a', 'href', '/basic/foo')
11 | .assert.attributeContains('li:nth-child(3) a', 'href', '/basic/bar')
12 | .assert.attributeContains('li:nth-child(4) a', 'href', '/basic/bar')
13 | .assert.containsText('.view', 'home')
14 |
15 | .click('li:nth-child(2) a')
16 | .assert.urlEquals('http://localhost:8080/basic/foo')
17 | .assert.containsText('.view', 'foo')
18 |
19 | .click('li:nth-child(3) a')
20 | .assert.urlEquals('http://localhost:8080/basic/bar')
21 | .assert.containsText('.view', 'bar')
22 |
23 | .click('li:nth-child(1) a')
24 | .assert.urlEquals('http://localhost:8080/basic/')
25 | .assert.containsText('.view', 'home')
26 |
27 | .click('li:nth-child(4) a')
28 | .assert.urlEquals('http://localhost:8080/basic/bar')
29 | .assert.containsText('.view', 'bar')
30 |
31 | // check initial visit
32 | .url('http://localhost:8080/basic/foo')
33 | .waitForElementVisible('#app', 1000)
34 | .assert.containsText('.view', 'foo')
35 | .end()
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/docs/en/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # vue-router 2
2 |
3 | > Note: vue-router@2.x only works with Vue 2.x. Docs for 0.7.x is [here](https://github.com/vuejs/vue-router/tree/1.0/docs/en).
4 |
5 | **[Release Notes](https://github.com/vuejs/vue-router/releases)**
6 |
7 | - [Installation](installation.md)
8 | - Essentials
9 | - [Getting Started](essentials/getting-started.md)
10 | - [Dynamic Route Matching](essentials/dynamic-matching.md)
11 | - [Nested Routes](essentials/nested-routes.md)
12 | - [Programmatic Navigation](essentials/navigation.md)
13 | - [Named Routes](essentials/named-routes.md)
14 | - [Named Views](essentials/named-views.md)
15 | - [Redirect and Alias](essentials/redirect-and-alias.md)
16 | - [Passing Props to Route Components](essentials/passing-props.md)
17 | - [HTML5 History Mode](essentials/history-mode.md)
18 | - Advanced
19 | - [Navigation Guards](advanced/navigation-guards.md)
20 | - [Route Meta Fields](advanced/meta.md)
21 | - [Transitions](advanced/transitions.md)
22 | - [Data Fetching](advanced/data-fetching.md)
23 | - [Scroll Behavior](advanced/scroll-behavior.md)
24 | - [Lazy Loading](advanced/lazy-loading.md)
25 | - API Reference
26 | - [router-link](api/router-link.md)
27 | - [router-view](api/router-view.md)
28 | - [The Route Object](api/route-object.md)
29 | - [Router Constructor Options](api/options.md)
30 | - [Router Instance](api/router-instance.md)
31 | - [Component Injections](api/component-injections.md)
32 |
--------------------------------------------------------------------------------
/src/history/abstract.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import type Router from '../index'
4 | import { History } from './base'
5 |
6 | export class AbstractHistory extends History {
7 | index: number;
8 | stack: Array;
9 |
10 | constructor (router: Router, base: ?string) {
11 | super(router, base)
12 | this.stack = []
13 | this.index = -1
14 | }
15 |
16 | push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
17 | this.transitionTo(location, route => {
18 | this.stack = this.stack.slice(0, this.index + 1).concat(route)
19 | this.index++
20 | onComplete && onComplete(route)
21 | }, onAbort)
22 | }
23 |
24 | replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
25 | this.transitionTo(location, route => {
26 | this.stack = this.stack.slice(0, this.index).concat(route)
27 | onComplete && onComplete(route)
28 | }, onAbort)
29 | }
30 |
31 | go (n: number) {
32 | const targetIndex = this.index + n
33 | if (targetIndex < 0 || targetIndex >= this.stack.length) {
34 | return
35 | }
36 | const route = this.stack[targetIndex]
37 | this.confirmTransition(route, () => {
38 | this.index = targetIndex
39 | this.updateRoute(route)
40 | })
41 | }
42 |
43 | getCurrentLocation () {
44 | const current = this.stack[this.stack.length - 1]
45 | return current ? current.fullPath : '/'
46 | }
47 |
48 | ensureURL () {
49 | // noop
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/docs/de/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # vue-router 2
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 |
--------------------------------------------------------------------------------
/examples/webpack.config.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | const path = require('path')
3 | const webpack = require('webpack')
4 |
5 | module.exports = {
6 |
7 | devtool: 'inline-source-map',
8 |
9 | entry: fs.readdirSync(__dirname).reduce((entries, dir) => {
10 | const fullDir = path.join(__dirname, dir)
11 | const entry = path.join(fullDir, 'app.js')
12 | if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
13 | entries[dir] = ['es6-promise/auto', entry]
14 | }
15 |
16 | return entries
17 | }, {}),
18 |
19 | output: {
20 | path: path.join(__dirname, '__build__'),
21 | filename: '[name].js',
22 | chunkFilename: '[id].chunk.js',
23 | publicPath: '/__build__/'
24 | },
25 |
26 | module: {
27 | rules: [
28 | { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
29 | { test: /\.vue$/, loader: 'vue-loader' }
30 | ]
31 | },
32 |
33 | resolve: {
34 | alias: {
35 | 'vue': 'vue/dist/vue.common.js',
36 | 'vue-router': path.join(__dirname, '..', 'src')
37 | }
38 | },
39 |
40 | // Expose __dirname to allow automatically setting basename.
41 | context: __dirname,
42 | node: {
43 | __dirname: true
44 | },
45 |
46 | plugins: [
47 | new webpack.optimize.CommonsChunkPlugin({
48 | name: 'shared',
49 | filename: 'shared.js'
50 | }),
51 | new webpack.DefinePlugin({
52 | 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
53 | })
54 | ]
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/docs/zh-cn/essentials/history-mode.md:
--------------------------------------------------------------------------------
1 | # HTML5 History 模式
2 |
3 | `vue-router` 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
4 |
5 | 如果不想要很丑的 hash,我们可以用路由的 **history 模式**,这种模式充分利用 `history.pushState` API 来完成 URL 跳转而无须重新加载页面。
6 |
7 | ``` js
8 | const router = new VueRouter({
9 | mode: 'history',
10 | routes: [...]
11 | })
12 | ```
13 |
14 | 当你使用 history 模式时,URL 就像正常的 url,例如 `http://yoursite.com/user/id`,也好看!
15 |
16 | 不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 `http://oursite.com/user/id` 就会返回 404,这就不好看了。
17 |
18 | 所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 `index.html` 页面,这个页面就是你 app 依赖的页面。
19 |
20 | ## 后端配置例子
21 |
22 | #### Apache
23 |
24 | ```apache
25 |
26 | RewriteEngine On
27 | RewriteBase /
28 | RewriteRule ^index\.html$ - [L]
29 | RewriteCond %{REQUEST_FILENAME} !-f
30 | RewriteCond %{REQUEST_FILENAME} !-d
31 | RewriteRule . /index.html [L]
32 |
33 | ```
34 |
35 | #### nginx
36 |
37 | ```nginx
38 | location / {
39 | try_files $uri $uri/ /index.html;
40 | }
41 | ```
42 |
43 | #### Node.js (Express)
44 |
45 | https://github.com/bripkens/connect-history-api-fallback
46 |
47 | ## 警告
48 |
49 | 给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 `index.html` 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后在给出一个 404 页面。
50 |
51 | ``` js
52 | const router = new VueRouter({
53 | mode: 'history',
54 | routes: [
55 | { path: '*', component: NotFoundComponent }
56 | ]
57 | })
58 | ```
59 |
60 | 或者,如果你是用 Node.js 作后台,可以使用服务端的路由来匹配 URL,当没有匹配到路由的时候返回 404,从而实现 fallback。
61 |
--------------------------------------------------------------------------------
/docs/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-require/)을 결합합니다. 라우트 컴포넌트를 쉽게 불러올 수 있습니다.
6 |
7 | 라우트 컴포넌트를 비동기 컴포넌트로 정의하면됩니다.
8 |
9 | ``` js
10 | const Foo = resolve => {
11 | // require.ensure는 Webpack의 코드 분할에 대한 특수 구문입니다.
12 | require.ensure(['./Foo.vue'], () => {
13 | resolve(require('./Foo.vue'))
14 | })
15 | }
16 | ```
17 |
18 | AMD 스타일 요구 사항을 사용하는 또다른 코드 분할 구문도 있으므로 다음과 같이 단순화 할 수 있습니다.
19 |
20 | ``` js
21 | const Foo = resolve => require(['./Foo.vue'], resolve)
22 | ```
23 |
24 | 라우트 설정에서 아무것도 바꿀 필요가 없습니다. 보통 `Foo`만 사용하십시오.
25 |
26 | ``` js
27 | const router = new VueRouter({
28 | routes: [
29 | { path: '/foo', component: Foo }
30 | ]
31 | })
32 | ```
33 |
34 | ### 같은 묶음으로 컴포넌트 그룹화하기
35 |
36 | 때로는 동일한 라우트 아래에 중첩된 모든 컴포넌트를 동일한 비동기 묶음으로 그룹화 할 수 있습니다. 이를 위해 우리는 세 번째 전달인자로 `require.ensure`에 묶음 이름을 제공하여 [이름을 가진 묶음](https://webpack.js.org/guides/code-splitting-require/#chunkname)을 사용해야합니다.
37 |
38 | ``` js
39 | const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
40 | const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
41 | const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
42 | ```
43 |
44 | Webpack은 동일한 묶음 이름을 가진 비동기 모듈을 같은 비동기 묶음으로 그룹화합니다. 이것은 또한`require.ensure`에 대한 종속성을 더 이상 명시 적으로 나열할 필요가 없음을 의미합니다(따라서 빈 배열을 전달합니다).
45 |
--------------------------------------------------------------------------------
/test/e2e/specs/named-routes.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'named routes': function (browser) {
3 | browser
4 | .url('http://localhost:8080/named-routes/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 3)
7 | // assert correct href with base
8 | .assert.attributeContains('li:nth-child(1) a', 'href', '/named-routes/')
9 | .assert.attributeContains('li:nth-child(2) a', 'href', '/named-routes/foo')
10 | .assert.attributeContains('li:nth-child(3) a', 'href', '/named-routes/bar')
11 | .assert.containsText('p', 'Current route name: home')
12 | .assert.containsText('.view', 'Home')
13 |
14 | .click('li:nth-child(2) a')
15 | .assert.urlEquals('http://localhost:8080/named-routes/foo')
16 | .assert.containsText('p', 'Current route name: foo')
17 | .assert.containsText('.view', 'Foo')
18 |
19 | .click('li:nth-child(3) a')
20 | .assert.urlEquals('http://localhost:8080/named-routes/bar/123')
21 | .assert.containsText('p', 'Current route name: bar')
22 | .assert.containsText('.view', 'Bar 123')
23 |
24 | .click('li:nth-child(1) a')
25 | .assert.urlEquals('http://localhost:8080/named-routes/')
26 | .assert.containsText('p', 'Current route name: home')
27 | .assert.containsText('.view', 'Home')
28 |
29 | // check initial visit
30 | .url('http://localhost:8080/named-routes/foo')
31 | .waitForElementVisible('#app', 1000)
32 | .assert.containsText('p', 'Current route name: foo')
33 | .assert.containsText('.view', 'Foo')
34 | .end()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/docs/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 }`
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 | }
57 | }
58 | }
59 | ```
60 |
61 | 또한 [라우트 메타 필드](meta.md)를 사용하여 세밀한 스크롤 동작 제어를 구현할 수 있습니다. 전체 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js)를 확인하십시오.
62 |
--------------------------------------------------------------------------------
/docs/ru/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Vue-router 2
2 |
3 | > Примечание: Vue-router@2.x работает только с Vue 2.x. Документация для версии 0.7.x находится [здесь (en)](https://github.com/vuejs/vue-router/tree/1.0/docs/en).
4 |
5 | **[История изменений](https://github.com/vuejs/vue-router/releases)**
6 |
7 | - [Введение](README.md)
8 | - [Установка](installation.md)
9 | - Основы
10 | - [Начало работы](essentials/getting-started.md)
11 | - [Динамические пути](essentials/dynamic-matching.md)
12 | - [Вложенные пути](essentials/nested-routes.md)
13 | - [Императивная навигация](essentials/navigation.md)
14 | - [Именованные пути](essentials/named-routes.md)
15 | - [Именованные представления](essentials/named-views.md)
16 | - [Редиректы и псевдонимы](essentials/redirect-and-alias.md)
17 | - [Передача входных параметров в компоненты маршрутов](essentials/passing-props.md)
18 | - [Режим HTML5 History](essentials/history-mode.md)
19 | - Продвинутые возможности
20 | - [Сторожевые хуки](advanced/navigation-guards.md)
21 | - [Метаданные путей](advanced/meta.md)
22 | - [Анимация переходов](advanced/transitions.md)
23 | - [Запросы данных](advanced/data-fetching.md)
24 | - [Скроллинг](advanced/scroll-behavior.md)
25 | - [Ленивая загрузка путей](advanced/lazy-loading.md)
26 | - Справочник API
27 | - [router-link](api/router-link.md)
28 | - [router-view](api/router-view.md)
29 | - [Объект route](api/route-object.md)
30 | - [Опции конструктора Router'а](api/options.md)
31 | - [Инстанс Router'а](api/router-instance.md)
32 | - [Интеграция с компонентами Vue](api/component-injections.md)
33 |
--------------------------------------------------------------------------------
/docs/ja/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-require/) を組み合わせることでとても簡単に遅延ロードするルートコンポーネントができます。
6 |
7 | 必要なことは非同期のルートコンポーネントを定義するだけです。
8 |
9 | ``` js
10 | const Foo = resolve => {
11 | // require.ensure はコード分割のための Webpack の特殊な文法です。
12 | require.ensure(['./Foo.vue'], () => {
13 | resolve(require('./Foo.vue'))
14 | })
15 | }
16 | ```
17 |
18 | コード分割の文法の代替として、 AMD 形式の require もあります。これを使うと次のように簡略されます。
19 |
20 | ``` js
21 | const Foo = resolve => require(['./Foo.vue'], resolve)
22 | ```
23 |
24 | 特にルート設定を変更する必要はなく、普段のように `Foo` を使用するだけです。
25 |
26 | ``` js
27 | const router = new VueRouter({
28 | routes: [
29 | { path: '/foo', component: Foo }
30 | ]
31 | })
32 | ```
33 |
34 | ### 同じチャンク内でのコンポーネントグループ化
35 |
36 | しばしば同じ非同期のチャンクに、そのルート配下のネストされた全てのコンポーネントをグループ化したいと思うかもしれません。それを実現するためには、 `require.ensure` の第 3 引数にチャンクの名前を提供する [名前付きチャンク](https://webpack.js.org/guides/code-splitting-require/#chunkname) を使う必要があります。
37 |
38 | ``` js
39 | const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
40 | const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
41 | const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
42 | ```
43 |
44 | Webpack は同じチャンク名のどんな非同期のモジュールも同じ非同期のチャンクにグループします。つまり、 `require.ensure` に対して明示的に依存関係をリストする必要がありません (したがって空の配列を渡しています)。
45 |
--------------------------------------------------------------------------------
/docs/ja/advanced/scroll-behavior.md:
--------------------------------------------------------------------------------
1 | # スクロールの振る舞い
2 |
3 | クライアントサイドのルーティングを使っている時に、新しいルートに対してスクロールをトップへ移動させたいかもしれません、もしくは実際のページリロードがしているように history 要素のスクロールポジションを保持したいこともあるかもしれません。 `vue-router` ではこれらをさらによく実現できます。ルートナビゲーションにおけるスクロールの挙動を完全にカスタマイズすることができます。
4 |
5 | **注意: この機能は HTML5 history モードでのみ動作します。**
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` のルートオブジェクトを受け取ります。第 3 引数の `savedPosition` は `popstate` ナビゲーション (ブラウザの戻る/進むボタンがトリガーされた) 時のみ利用可能です。
19 |
20 | この関数はスクロールポジションオブジェクトを返すことができます。そのオブジェクトは以下のような形式です。
21 |
22 | - `{ x: number, y: number }`
23 | - `{ selector: string }`
24 |
25 | もし falsy な値や空のオブジェクトが返った場合、何もスクロールは起きません。
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 | もし"アンカーへスクロール"の振る舞いをシミュレートしたい場合は以下のようにしてください。
50 |
51 | ``` js
52 | scrollBehavior (to, from, savedPosition) {
53 | if (to.hash) {
54 | return {
55 | selector: to.hash
56 | }
57 | }
58 | }
59 | ```
60 |
61 | きめの細かいスクロールの挙動コントロールを実装するために [ルートメタフィールド](meta.md) も利用可能です。詳細な例は [こちら](https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js) をご参照ください。
62 |
--------------------------------------------------------------------------------
/src/util/push-state.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import { inBrowser } from './dom'
4 | import { saveScrollPosition } from './scroll'
5 |
6 | export const supportsPushState = inBrowser && (function () {
7 | const ua = window.navigator.userAgent
8 |
9 | if (
10 | (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
11 | ua.indexOf('Mobile Safari') !== -1 &&
12 | ua.indexOf('Chrome') === -1 &&
13 | ua.indexOf('Windows Phone') === -1
14 | ) {
15 | return false
16 | }
17 |
18 | return window.history && 'pushState' in window.history
19 | })()
20 |
21 | // use User Timing api (if present) for more accurate key precision
22 | const Time = inBrowser && window.performance && window.performance.now
23 | ? window.performance
24 | : Date
25 |
26 | let _key: string = genKey()
27 |
28 | function genKey (): string {
29 | return Time.now().toFixed(3)
30 | }
31 |
32 | export function getStateKey () {
33 | return _key
34 | }
35 |
36 | export function setStateKey (key: string) {
37 | _key = key
38 | }
39 |
40 | export function pushState (url?: string, replace?: boolean) {
41 | saveScrollPosition()
42 | // try...catch the pushState call to get around Safari
43 | // DOM Exception 18 where it limits to 100 pushState calls
44 | const history = window.history
45 | try {
46 | if (replace) {
47 | history.replaceState({ key: _key }, '', url)
48 | } else {
49 | _key = genKey()
50 | history.pushState({ key: _key }, '', url)
51 | }
52 | } catch (e) {
53 | window.location[replace ? 'replace' : 'assign'](url)
54 | }
55 | }
56 |
57 | export function replaceState (url?: string) {
58 | pushState(url, true)
59 | }
60 |
--------------------------------------------------------------------------------
/docs/kr/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # 라우터 인스턴스
2 |
3 | ### 속성
4 |
5 | #### router.app
6 |
7 | - 자료형: `Vue instance`
8 |
9 | `router`가 주입 된 루트 Vue 인스턴스.
10 |
11 | #### router.mode
12 |
13 | - 자료형: `string`
14 |
15 | 라우터가 사용하는 [mode](options.md#mode).
16 |
17 | #### router.currentRoute
18 |
19 | - 자료형: `Route`
20 |
21 | [라우트 객체](route-object.md)로 표시된 현재 라우트.
22 |
23 | ### Methods
24 |
25 | - **router.beforeEach(guard)**
26 | - **router.afterEach(hook)**
27 |
28 | 전역 네비게이션 가드 추가. [네비게이션 가드](../advanced/navigation-guards.md)를 보십시오.
29 |
30 |
31 | - **router.push(location, onComplete?, onAbort?)**
32 | - **router.replace(location, onComplete?, onAbort?)**
33 | - **router.go(n)**
34 | - **router.back()**
35 | - **router.forward()**
36 |
37 | 프로그래밍 방식으로 새 URL로 이동합니다. [프로그래밍 방식 네비게이션](../essentials/navigation.md)을 참조하십시오.
38 |
39 | - **router.getMatchedComponents(location?)**
40 |
41 | 지정된 위치 또는 현재의 라우트에 일치하는 컴퍼넌트(인스턴스는 아니고 정의/생성자)의 배열을 반환합니다. 이는 주로 데이터를 프리페치(prefetching)하기 위해 서버 측 렌더링 동안 사용됩니다.
42 |
43 | - **router.resolve(location, current?, append?)**
44 |
45 | > 2.1.0+
46 |
47 | 역방향 URL 해석. ` `에서 사용된 것과 같은 형식의 위치가 주어지면 다음과 같이 처리된 속성을 가진 객체를 반환합니다.
48 |
49 | ``` js
50 | {
51 | location: Location;
52 | route: Route;
53 | href: string;
54 | }
55 | ```
56 |
57 | - **router.addRoutes(routes)**
58 |
59 | > 2.2.0+
60 |
61 | 라우터에 동적으로 더 많은 라우트를 추가할 수 있습니다. 전달인자는 `routes` 생성자 옵션과 동일한 경로 설정 포맷을 사용하는 배열이어야 합니다.
62 |
63 | - **router.onReady(callback)**
64 |
65 | > 2.2.0+
66 |
67 | 이 메소드는 라우터가 초기 탐색을 완료할 때 호출하는 콜백을 대기시킵니다. 즉, 초기 라우트와 연결된 모든 비동기 입력 훅 및 비동기 컴포넌트를 해결합니다.
68 |
69 | 이는 서버와 클라이언트 모두 일관된 출력을 보장하기 위해 서버측 렌더링을 사용할 때 유용합니다.
70 |
--------------------------------------------------------------------------------
/docs/en/advanced/meta.md:
--------------------------------------------------------------------------------
1 | # Route Meta Fields
2 |
3 | You can include a `meta` field when defining a 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 | // a meta field
16 | meta: { requiresAuth: true }
17 | }
18 | ]
19 | }
20 | ]
21 | })
22 | ```
23 |
24 | So how do we access this `meta` field?
25 |
26 | First, each route object in the `routes` configuration is called a **route record**. Route records may be nested. Therefore when a route is matched, it can potentially match more than one route record.
27 |
28 | For example, with the above route config, the URL `/foo/bar` will match both the parent route record and the child route record.
29 |
30 | All route records matched by a route are exposed on the `$route` object (and also route objects in navigation guards) as the `$route.matched` Array. Therefore, we will need to iterate over `$route.matched` to check for meta fields in route records.
31 |
32 | An example use case is checking for a meta field in the global navigation guard:
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() // make sure to always call next()!
49 | }
50 | })
51 | ```
52 |
--------------------------------------------------------------------------------
/examples/data-fetching/Post.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Loading...
4 |
5 | {{ error }}
6 |
7 |
8 |
12 |
13 |
{{ post.title }}
14 |
{{ post.body }}
15 |
16 |
17 |
18 |
19 |
20 |
53 |
54 |
76 |
--------------------------------------------------------------------------------
/docs/ja/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # ルーターインスタンス
2 |
3 | ### プロパティ
4 |
5 | #### router.app
6 |
7 | - 型: `Vue インスタンス`
8 |
9 | `router` が注入される root の Vue インスタンス
10 |
11 | #### router.mode
12 |
13 | - 型: `string`
14 |
15 | ルーターが使う [モード](options.md#mode) 。
16 |
17 | #### router.currentRoute
18 |
19 | - 型: `Route`
20 |
21 | [ルーターオブジェクト](route-object.md) として表される現在のルート。
22 |
23 | ### メソッド
24 |
25 | - **router.beforeEach(guard)**
26 | - **router.afterEach(hook)**
27 |
28 | グローバルなナビゲーションガードの追加。[ナビゲーションガード](../advanced/navigation-guards.md) をご参照ください。
29 |
30 |
31 | - **router.push(location, onComplete?, onAbort?)**
32 | - **router.replace(location, onComplete?, onAbort?)**
33 | - **router.go(n)**
34 | - **router.back()**
35 | - **router.forward()**
36 |
37 | プログラムによる新しい URL へのナビゲーション。 [プログラムによるナビゲーション](../essentials/navigation.md) をご参照ください。
38 |
39 | - **router.getMatchedComponents(location?)**
40 |
41 | 現在のルートまたは提供されたロケーションにマッチしているコンポーネント (インスタンスではなく定義 / コンストラクタ) の配列を返します。これは大抵の場合データ取得を行うサーバーサイドレンダリングで使用されます。
42 |
43 | - **router.resolve(location, current?, append?)**
44 |
45 | > 2.1.0+
46 |
47 | 逆 URL 解決します。` ` で使われているものと同じ形式の location が与えられた場合は、以下の解決されたプロパティを返します。
48 |
49 | ``` js
50 | {
51 | location: Location;
52 | route: Route;
53 | href: string;
54 | }
55 | ```
56 |
57 | - **router.addRoutes(routes)**
58 |
59 | > 2.2.0+
60 |
61 | 動的にルートをルーターに追加します。引数は `routes` コンストラクタオプションで同じルート設定形式を使用する配列でなければなりません。
62 |
63 | - **router.onReady(callback)**
64 |
65 | > 2.2.0+
66 |
67 | このメソッドは、ルーターが初期ナビゲーションを完了したときに呼び出されるコールバックをキューに入れます。つまり、初期ルートに関連付けられているすべての非同期 enter フックと非同期コンポーネントを解決したことを意味します。
68 |
69 | これは、サーバーとクライアントの両方で一貫した出力を保証するために、サーバーサイドレンダリングに役立ちます。
70 |
--------------------------------------------------------------------------------
/docs/zh-cn/api/options.md:
--------------------------------------------------------------------------------
1 | # Router 构造配置
2 |
3 | ### routes
4 |
5 | - 类型: `Array`
6 |
7 | `RouteConfig` 的类型定义:
8 |
9 | ``` js
10 | declare type RouteConfig = {
11 | path: string;
12 | component?: Component;
13 | name?: string; // for named routes (命名路由)
14 | components?: { [name: string]: Component }; // for named views (命名视图组件)
15 | redirect?: string | Location | Function;
16 | alias?: string | Array;
17 | children?: Array; // for nested routes
18 | beforeEnter?: (to: Route, from: Route, next: Function) => void;
19 | meta?: any;
20 | }
21 | ```
22 |
23 | ### mode
24 |
25 | - 类型: `string`
26 |
27 | - 默认值: `"hash" (浏览器环境) | "abstract" (Node.js 环境)`
28 |
29 | - 可选值: `"hash" | "history" | "abstract"`
30 |
31 | 配置路由模式:
32 |
33 | - `hash`: 使用 URL hash 值来作路由。支持所有浏览器,包括不支持 HTML5 History Api 的浏览器。
34 |
35 | - `history`: 依赖 HTML5 History API 和服务器配置。查看 [HTML5 History 模式](../essentials/history-mode.md).
36 |
37 | - `abstract`: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。**如果发现没有浏览器的 API,路由会自动强制进入这个模式。**
38 |
39 | ### base
40 |
41 | - 类型: `string`
42 |
43 | - 默认值: `"/"`
44 |
45 | 应用的基路径。例如,如果整个单页应用服务在 `/app/` 下,然后 `base` 就应该设为 `"/app/"`。
46 |
47 | ### linkActiveClass
48 |
49 | - 类型: `string`
50 |
51 | - 默认值: `"router-link-active"`
52 |
53 | 全局配置 `` 的默认『激活 class 类名』。参考 [router-link](router-link.md).
54 |
55 | ### scrollBehavior
56 |
57 | - 类型: `Function`
58 |
59 | 签名:
60 |
61 | ```
62 | (
63 | to: Route,
64 | from: Route,
65 | savedPosition?: { x: number, y: number }
66 | ) => { x: number, y: number } | { selector: string } | ?{}
67 | ```
68 |
69 | 更多详情参考 [滚动行为](../advanced/scroll-behavior.md).
70 |
--------------------------------------------------------------------------------
/docs/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 |
58 | ``` js
59 | const router = new VueRouter({
60 | routes: [
61 | { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
62 | ]
63 | })
64 | ```
65 |
66 | `/search?q=vue`는 `{query: "vue"}`를 SearchUser 컴포넌트에 전달합니다.
67 |
68 | 라우트 변경시에만 평가되므로 props 함수는 상태를 저장하지 않도록 합니다.
69 | props를 정의할 상태가 필요한 경우 래퍼 컴포넌트를 사용하면 상태가 변경될 때마다 응답할 수 있습니다.
70 |
71 | 고급 사용예를 보려면 [예제](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js)를 확인하세요.
72 |
--------------------------------------------------------------------------------
/docs/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/en/essentials/redirect-and-alias.md:
--------------------------------------------------------------------------------
1 | # Redirect and Alias
2 |
3 | ### Redirect
4 |
5 | Redirecting is also done in the `routes` configuration. To redirect from `/a` to `/b`:
6 |
7 | ``` js
8 | const router = new VueRouter({
9 | routes: [
10 | { path: '/a', redirect: '/b' }
11 | ]
12 | })
13 | ```
14 |
15 | The redirect can also be targeting a named route:
16 |
17 | ``` js
18 | const router = new VueRouter({
19 | routes: [
20 | { path: '/a', redirect: { name: 'foo' }}
21 | ]
22 | })
23 | ```
24 |
25 | Or even use a function for dynamic redirecting:
26 |
27 | ``` js
28 | const router = new VueRouter({
29 | routes: [
30 | { path: '/a', redirect: to => {
31 | // the function receives the target route as the argument
32 | // return redirect path/location here.
33 | }}
34 | ]
35 | })
36 | ```
37 |
38 | For other advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js).
39 |
40 | ### Alias
41 |
42 | A redirect means when the user visits `/a`, and URL will be replaced by `/b`, and then matched as `/b`. But what is an alias?
43 |
44 | **An alias of `/a` as `/b` means when the user visits `/b`, the URL remains `/b`, but it will be matched as if the user is visiting `/a`.**
45 |
46 | The above can be expressed in the route configuration as:
47 |
48 | ``` js
49 | const router = new VueRouter({
50 | routes: [
51 | { path: '/a', component: A, alias: '/b' }
52 | ]
53 | })
54 | ```
55 |
56 | An alias gives you the freedom to map a UI structure to an arbitrary URL, instead of being constrained by the configuration's nesting structure.
57 |
58 | For advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js).
59 |
--------------------------------------------------------------------------------
/src/util/path.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | export function resolvePath (
4 | relative: string,
5 | base: string,
6 | append?: boolean
7 | ): string {
8 | const firstChar = relative.charAt(0)
9 | if (firstChar === '/') {
10 | return relative
11 | }
12 |
13 | if (firstChar === '?' || firstChar === '#') {
14 | return base + relative
15 | }
16 |
17 | const stack = base.split('/')
18 |
19 | // remove trailing segment if:
20 | // - not appending
21 | // - appending to trailing slash (last segment is empty)
22 | if (!append || !stack[stack.length - 1]) {
23 | stack.pop()
24 | }
25 |
26 | // resolve relative path
27 | const segments = relative.replace(/^\//, '').split('/')
28 | for (let i = 0; i < segments.length; i++) {
29 | const segment = segments[i]
30 | if (segment === '..') {
31 | stack.pop()
32 | } else if (segment !== '.') {
33 | stack.push(segment)
34 | }
35 | }
36 |
37 | // ensure leading slash
38 | if (stack[0] !== '') {
39 | stack.unshift('')
40 | }
41 |
42 | return stack.join('/')
43 | }
44 |
45 | export function parsePath (path: string): {
46 | path: string;
47 | query: string;
48 | hash: string;
49 | } {
50 | let hash = ''
51 | let query = ''
52 |
53 | const hashIndex = path.indexOf('#')
54 | if (hashIndex >= 0) {
55 | hash = path.slice(hashIndex)
56 | path = path.slice(0, hashIndex)
57 | }
58 |
59 | const queryIndex = path.indexOf('?')
60 | if (queryIndex >= 0) {
61 | query = path.slice(queryIndex + 1)
62 | path = path.slice(0, queryIndex)
63 | }
64 |
65 | return {
66 | path,
67 | query,
68 | hash
69 | }
70 | }
71 |
72 | export function cleanPath (path: string): string {
73 | return path.replace(/\/\//g, '/')
74 | }
75 |
--------------------------------------------------------------------------------
/docs/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/kr/essentials/history-mode.md:
--------------------------------------------------------------------------------
1 | # HTML5 히스토리 모드
2 |
3 | `vue-router`의 기본 모드는 _hash mode_ 입니다. URL 해시를 사용하여 전체 URL을 시뮬레이트하므로 URL이 변경될 때 페이지가 다시 로드 되지 않습니다.
4 |
5 | 해시를 제거하기 위해 라우터의 **history 모드** 를 사용할 수 있습니다. `history.pushState` API를 활용하여 페이지를 다시 로드하지 않고도 URL 탐색을 할 수 있습니다.
6 |
7 | ``` js
8 | const router = new VueRouter({
9 | mode: 'history',
10 | routes: [...]
11 | })
12 | ```
13 |
14 | 히스토리 모드를 사용하면 URL이 "정상"으로 보입니다. `http://oursite.com/user/id`. 멋집니다!
15 |
16 | 그러나 문제는 다음과 같습니다. 우리의 앱이 적절한 서버 설정이 없는 단일 페이지 클라이언트 앱이기 때문에 사용자가 직접 `http://oursite.com/user/id` 에 접속하면 404 오류가 발생합니다.
17 |
18 | 걱정하지 않아도됩니다. 문제를 해결하려면 서버에 간단하게 포괄적인 대체 경로를 추가하기만 하면됩니다. URL이 정적 에셋과 일치하지 않으면 앱이 있는 동일한 `index.html`페이지를 제공해야 합니다.
19 |
20 | ## 서버 설정 예제
21 |
22 | #### Apache
23 |
24 | ```apache
25 |
26 | RewriteEngine On
27 | RewriteBase /
28 | RewriteRule ^index\.html$ - [L]
29 | RewriteCond %{REQUEST_FILENAME} !-f
30 | RewriteCond %{REQUEST_FILENAME} !-d
31 | RewriteRule . /index.html [L]
32 |
33 | ```
34 |
35 | #### nginx
36 |
37 | ```nginx
38 | location / {
39 | try_files $uri $uri/ /index.html;
40 | }
41 | ```
42 |
43 | #### Node.js (Express)
44 |
45 | Node.js/Express의 경우 [connect-history-api-fallback 미들웨어](https://github.com/bripkens/connect-history-api-fallback)를 고려해보세요.
46 |
47 | ## 주의 사항
48 |
49 | 주의 사항이 있습니다. 여러분의 서버는 404 에러를 보고하지 않을 것입니다. 왜냐하면 모든 발견되지 않은 경로가 이제 `index.html` 파일을 제공하기 때문입니다. 이 문제를 해결하려면 Vue 앱에서 catch-all 라우트를 구현하여 404 페이지를 표시해야합니다.
50 |
51 |
52 | ``` js
53 | const router = new VueRouter({
54 | mode: 'history',
55 | routes: [
56 | { path: '*', component: NotFoundComponent }
57 | ]
58 | })
59 | ```
60 |
61 | 또는 Node.js 서버를 사용하는 경우 서버 측의 라우터를 사용하여 들어오는 URL을 일치시키고 라우트가 일치하지 않으면 404로 응답하여 폴백을 구현할 수 있습니다.
62 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/en/advanced/transitions.md:
--------------------------------------------------------------------------------
1 | # Transitions
2 |
3 | Since the `` is essentially a dynamic component, we can apply transition effects to it the same way using the `` component:
4 |
5 | ``` html
6 |
7 |
8 |
9 | ```
10 |
11 | [Everything about ``](http://vuejs.org/guide/transitions.html) works the same here.
12 |
13 | ### Per-Route Transition
14 |
15 | The above usage will apply the same transition for all routes. If you want each route's component to have different transitions, you can instead use `` with different names inside each route component:
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-Based Dynamic Transition
36 |
37 | It is also possible to determine the transition to use dynamically based on the relationship between the target route and current route:
38 |
39 | ``` html
40 |
41 |
42 |
43 |
44 | ```
45 |
46 | ``` js
47 | // then, in the parent component,
48 | // watch the $route to determine the transition to use
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 | See full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js).
59 |
--------------------------------------------------------------------------------
/docs/kr/api/options.md:
--------------------------------------------------------------------------------
1 | # 라우터 생성자 옵션
2 |
3 | ### routes
4 |
5 | - 자료형: `Array`
6 |
7 | `RouteConfig`에 대한 자료형 선언:
8 |
9 | ``` js
10 | declare type RouteConfig = {
11 | path: string;
12 | component?: Component;
13 | name?: string; // 이름을 가진 라우트를 위함
14 | components?: { [name: string]: Component }; // 이름을 가진 뷰를 위함
15 | redirect?: string | Location | Function;
16 | alias?: string | Array;
17 | children?: Array; // 중첩된 라우트를 위함 routes
18 | beforeEnter?: (to: Route, from: Route, next: Function) => void;
19 | meta?: any;
20 | }
21 | ```
22 |
23 | ### mode
24 |
25 | - 자료형: `string`
26 |
27 | - 기본값: `"hash" (in browser) | "abstract" (in Node.js)`
28 |
29 | - 유효 값: `"hash" | "history" | "abstract"`
30 |
31 | 라우터 모드에 대한 설정입니다.
32 |
33 | - `hash`: 라우팅에 URL 해시를 사용합니다. HTML5 기록 API를 지원하지 않는 브라우저를 포함하여 모든 Vue 지원 브라우저에서 작동합니다.
34 |
35 | - `history`: HTML5 히스토리 API 및 서버 설정이 필요합니다. [HTML5 History 모드](../essentials/history-mode.md)를 확인하세요.
36 |
37 | - `abstract`: 모든 자바 스크립트 환경에서 작동합니다 (예: Node.js가 있는 서버 측 **브라우저 API가없는 경우 라우터가 자동으로이 모드로 강제 전환됩니다.**
38 |
39 | ### base
40 |
41 | - 자료형: `string`
42 |
43 | - 기본값: `"/"`
44 |
45 | 앱의 기본 URL입니다. 예를 들어, 전체 단일 페이지 응용 프로그램이 `/app/`하에 제공된다면`base`는 `"/app/"` 값을 사용해야합니다.
46 |
47 | ### linkActiveClass
48 |
49 | - 자료형: `string`
50 |
51 | - 기본값: `"router-link-active"`
52 |
53 | 전역의 `` 기본 active 클래스를 설정하십시오. [router-link](router-link.md)를 확인하세요.
54 |
55 | ### scrollBehavior
56 |
57 | - 자료형: `Function`
58 |
59 | 서명:
60 |
61 | ```
62 | (
63 | to: Route,
64 | from: Route,
65 | savedPosition?: { x: number, y: number }
66 | ) => { x: number, y: number } | { selector: string } | ?{}
67 | ```
68 |
69 | [Scroll 동작](../advanced/scroll-behavior.md)를 확인하세요.
70 |
--------------------------------------------------------------------------------
/docs/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 | Komplette Beispiel [hier](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js) ansehen.
59 |
--------------------------------------------------------------------------------
/test/e2e/specs/scroll-behavior.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'scroll behavior': function (browser) {
3 | browser
4 | .url('http://localhost:8080/scroll-behavior/')
5 | .waitForElementVisible('#app', 1000)
6 | .assert.count('li a', 4)
7 | .assert.containsText('.view', 'home')
8 |
9 | .execute(function () {
10 | window.scrollTo(0, 100)
11 | })
12 | .click('li:nth-child(2) a')
13 | .assert.containsText('.view', 'foo')
14 | .execute(function () {
15 | window.scrollTo(0, 200)
16 | window.history.back()
17 | })
18 | .assert.containsText('.view', 'home')
19 | .assert.evaluate(function () {
20 | return window.pageYOffset === 100
21 | }, null, 'restore scroll position on back')
22 |
23 | // scroll on a popped entry
24 | .execute(function () {
25 | window.scrollTo(0, 50)
26 | window.history.forward()
27 | })
28 | .assert.containsText('.view', 'foo')
29 | .assert.evaluate(function () {
30 | return window.pageYOffset === 200
31 | }, null, 'restore scroll position on forward')
32 |
33 | .execute(function () {
34 | window.history.back()
35 | })
36 | .assert.containsText('.view', 'home')
37 | .assert.evaluate(function () {
38 | return window.pageYOffset === 50
39 | }, null, 'restore scroll position on back again')
40 |
41 | .click('li:nth-child(3) a')
42 | .assert.evaluate(function () {
43 | return window.pageYOffset === 0
44 | }, null, 'scroll to top on new entry')
45 |
46 | .click('li:nth-child(4) a')
47 | .assert.evaluate(function () {
48 | return document.getElementById('anchor').getBoundingClientRect().top < 1
49 | }, null, 'scroll to anchor')
50 | .end()
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/docs/ja/essentials/history-mode.md:
--------------------------------------------------------------------------------
1 | # HTML5 History モード
2 |
3 | `vue-router` のデフォルトは _hash モード_ です - 完全な URL を hash を使ってシミュレートし、 URL が変更された時にページのリロードが起きません。
4 |
5 | その hash を取り除くために、ページのリロード無しに URL 遷移を実現する `history.pushState` API を利用したルーターの **history モード** を使うことができます。
6 |
7 | ``` js
8 | const router = new VueRouter({
9 | mode: 'history',
10 | routes: [...]
11 | })
12 | ```
13 |
14 | history モードを使用する時は、URL は "普通" に見えます e.g. `http://oursite.com/user/id`。美しいですね!
15 |
16 | しかしながら一点問題があります。シングルページのクライアントサイドアプリケーションなので、適切なサーバーの設定をしないと、ユーザーがブラウザで直接 `http://oursite.com/user/id` にアクセスした場合に 404 エラーが発生します。
17 |
18 | 心配する必要はありません。この問題を直すためには、単純な catch-all フォールバックのためのルートをサーバー側で追加するだけです。もし URL がどの静的なアセットにもマッチしなかった時はあなたのアプリケーションが動作しているのと同じ `index.html` ページで受け付けましょう。これも美しいですね!
19 |
20 | ## サーバーの設定例
21 |
22 | #### Apache
23 |
24 | ```apache
25 |
26 | RewriteEngine On
27 | RewriteBase /
28 | RewriteRule ^index\.html$ - [L]
29 | RewriteCond %{REQUEST_FILENAME} !-f
30 | RewriteCond %{REQUEST_FILENAME} !-d
31 | RewriteRule . /index.html [L]
32 |
33 | ```
34 |
35 | #### nginx
36 |
37 | ```nginx
38 | location / {
39 | try_files $uri $uri/ /index.html;
40 | }
41 | ```
42 |
43 | #### Node.js (Express)
44 |
45 | Node.js/Express では [connect-history-api-fallback middleware](https://github.com/bripkens/connect-history-api-fallback) の利用を検討してください。
46 |
47 | ## 注意
48 |
49 | この点に関して注意があります。全ての not-found パスが `index.html` を提供するため、もはや 404 エラーをサーバーがレポートしなくなります。回避策として、Vue アプリケーション内で 404 ページを表示するために catch-all ルートを実装すべきです。
50 |
51 | ``` js
52 | const router = new VueRouter({
53 | mode: 'history',
54 | routes: [
55 | { path: '*', component: NotFoundComponent }
56 | ]
57 | })
58 | ```
59 |
60 | 他の方法として、もしあなたが Node.js サーバーを使っている場合、入ってきた URL とマッチさせて、マッチしなかった場合に 404 を返答するサーバーサイドのルーターを使って fallback を実装することもできます。
61 |
--------------------------------------------------------------------------------
/test/e2e/specs/transitions.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'transitions': function (browser) {
3 | const TIMEOUT = 2000
4 |
5 | browser
6 | .url('http://localhost:8080/transitions/')
7 | .waitForElementVisible('#app', 1000)
8 | .assert.count('li a', 4)
9 |
10 | .click('li:nth-child(2) a')
11 | .assert.cssClassPresent('.view.home', 'fade-leave-active')
12 | .waitForElementPresent('.view.parent', TIMEOUT)
13 | .assert.cssClassPresent('.view.parent', 'fade-enter-active')
14 | .assert.cssClassNotPresent('.child-view.default', 'slide-left-enter-active')
15 | .waitForElementNotPresent('.view.parent.fade-enter-active', TIMEOUT)
16 |
17 | .click('li:nth-child(3) a')
18 | .assert.cssClassPresent('.child-view.default', 'slide-left-leave-active')
19 | .assert.cssClassPresent('.child-view.foo', 'slide-left-enter-active')
20 | .waitForElementNotPresent('.child-view.default', TIMEOUT)
21 |
22 | .click('li:nth-child(4) a')
23 | .assert.cssClassPresent('.child-view.foo', 'slide-left-leave-active')
24 | .assert.cssClassPresent('.child-view.bar', 'slide-left-enter-active')
25 | .waitForElementNotPresent('.child-view.foo', TIMEOUT)
26 |
27 | .click('li:nth-child(2) a')
28 | .assert.cssClassPresent('.child-view.bar', 'slide-right-leave-active')
29 | .assert.cssClassPresent('.child-view.default', 'slide-right-enter-active')
30 | .waitForElementNotPresent('.child-view.bar', TIMEOUT)
31 |
32 | .click('li:nth-child(1) a')
33 | .assert.cssClassPresent('.view.parent', 'fade-leave-active')
34 | .waitForElementPresent('.view.home', TIMEOUT)
35 | .assert.cssClassPresent('.view.home', 'fade-enter-active')
36 | .waitForElementNotPresent('.view.home.fade-enter-active', TIMEOUT)
37 |
38 | .end()
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/docs/ja/api/options.md:
--------------------------------------------------------------------------------
1 | # ルーターコンストラクタオプション
2 |
3 | ### routes
4 |
5 | - 型: `Array`
6 |
7 | `RouteConfig` の型宣言:
8 |
9 | ``` js
10 | declare type RouteConfig = {
11 | path: string;
12 | component?: Component;
13 | name?: string; // 名前付きルート用
14 | components?: { [name: string]: Component }; // 名前付き view 用
15 | redirect?: string | Location | Function;
16 | alias?: string | Array;
17 | children?: Array; // ネストされたルート用
18 | beforeEnter?: (to: Route, from: Route, next: Function) => void;
19 | meta?: any;
20 | }
21 | ```
22 |
23 | ### mode
24 |
25 | - 型: `string`
26 |
27 | - デフォルト: `"hash" (in browser) | "abstract" (in Node.js)`
28 |
29 | - 利用可能な値: `"hash" | "history" | "abstract"`
30 |
31 | ルーターモードの設定。
32 |
33 | - `hash`: ルーティングに URL hash を使います。HTML5 History API をサポートしていないブラウザ含めて、全ての Vue がサポートしているブラウザで動作します。
34 |
35 | - `history`: HTML5 History API とサーバーの設定が必要です。[HTML5 History モード](../essentials/history-mode.md) をご参照ください。
36 |
37 | - `abstract`: 全ての JavaScript の環境で動作します。 e.g. Node.js を使ったサーバーサイド。 **もしブラウザの API が存在しない場合、ルーターは自動的にこのモードに強制されます。**
38 |
39 | ### base
40 |
41 | - 型: `string`
42 |
43 | - デフォルト: `"/"`
44 |
45 | アプリケーションのベース URL です。例えば、 `/app/` 配下で完全なシングルページアプリケーションを提供する場合、 `base` は `"/app/"` の値が使われるべきです。
46 |
47 | ### linkActiveClass
48 |
49 | - 型: `string`
50 |
51 | - デフォルト: `"router-link-active"`
52 |
53 | グローバルに設定される `` のデフォルトのアクティブクラスです。こちらの [router-link](router-link.md) もご参照ください。
54 |
55 | ### scrollBehavior
56 |
57 | - 型: `Function`
58 |
59 | シグネチャ:
60 |
61 | ```
62 | (
63 | to: Route,
64 | from: Route,
65 | savedPosition?: { x: number, y: number }
66 | ) => { x: number, y: number } | { selector: string } | ?{}
67 | ```
68 |
69 | より詳細ついては [スクロールの振る舞い](../advanced/scroll-behavior.md) をご参照ください。
70 |
--------------------------------------------------------------------------------
/src/util/location.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import { parsePath, resolvePath } from './path'
4 | import { resolveQuery } from './query'
5 | import { fillParams } from './params'
6 | import { warn } from './warn'
7 |
8 | export function normalizeLocation (
9 | raw: RawLocation,
10 | current?: Route,
11 | append?: boolean
12 | ): Location {
13 | let next: Location = typeof raw === 'string' ? { path: raw } : raw
14 | // named target
15 | if (next.name || next._normalized) {
16 | return next
17 | }
18 |
19 | // relative params
20 | if (!next.path && next.params && current) {
21 | next = assign({}, next)
22 | next._normalized = true
23 | const params: any = assign(assign({}, current.params), next.params)
24 | if (current.name) {
25 | next.name = current.name
26 | next.params = params
27 | } else if (current.matched) {
28 | const rawPath = current.matched[current.matched.length - 1].path
29 | next.path = fillParams(rawPath, params, `path ${current.path}`)
30 | } else if (process.env.NODE_ENV !== 'production') {
31 | warn(false, `relative params navigation requires a current route.`)
32 | }
33 | return next
34 | }
35 |
36 | const parsedPath = parsePath(next.path || '')
37 | const basePath = (current && current.path) || '/'
38 | const path = parsedPath.path
39 | ? resolvePath(parsedPath.path, basePath, append || next.append)
40 | : (current && current.path) || '/'
41 | const query = resolveQuery(parsedPath.query, next.query)
42 | let hash = next.hash || parsedPath.hash
43 | if (hash && hash.charAt(0) !== '#') {
44 | hash = `#${hash}`
45 | }
46 |
47 | return {
48 | _normalized: true,
49 | path,
50 | query,
51 | hash
52 | }
53 | }
54 |
55 | function assign (a, b) {
56 | for (const key in b) {
57 | a[key] = b[key]
58 | }
59 | return a
60 | }
61 |
--------------------------------------------------------------------------------
/docs/zh-cn/essentials/getting-started.md:
--------------------------------------------------------------------------------
1 | # Getting Started
2 |
3 | > 教程中的案例代码将使用 [ES2015](https://github.com/lukehoban/es6features) 来编写。
4 |
5 | 用 Vue.js + vue-router 创建单页应用,是非常简单的。使用 Vue.js 时,我们就已经把组件组合成一个应用了,当你要把 vue-router 加进来,只需要配置组件和路由映射,然后告诉 vue-router 在哪里渲染它们。下面是个基本例子:
6 |
7 | ### HTML
8 |
9 | ``` html
10 |
11 |
12 |
13 |
14 |
Hello App!
15 |
16 |
17 |
18 |
19 | Go to Foo
20 | Go to Bar
21 |
22 |
23 |
24 |
25 |
26 | ```
27 |
28 | ### JavaScript
29 |
30 | ``` js
31 | // 0. 如果使用模块化机制编程,導入Vue和VueRouter,要调用 Vue.use(VueRouter)
32 |
33 | // 1. 定义(路由)组件。
34 | // 可以从其他文件 import 进来
35 | const Foo = { template: 'foo
' }
36 | const Bar = { template: 'bar
' }
37 |
38 | // 2. 定义路由
39 | // 每个路由应该映射一个组件。 其中"component" 可以是
40 | // 通过 Vue.extend() 创建的组件构造器,
41 | // 或者,只是一个组件配置对象。
42 | // 我们晚点再讨论嵌套路由。
43 | const routes = [
44 | { path: '/foo', component: Foo },
45 | { path: '/bar', component: Bar }
46 | ]
47 |
48 | // 3. 创建 router 实例,然后传 `routes` 配置
49 | // 你还可以传别的配置参数, 不过先这么简单着吧。
50 | const router = new VueRouter({
51 | routes // (缩写)相当于 routes: routes
52 | })
53 |
54 | // 4. 创建和挂载根实例。
55 | // 记得要通过 router 配置参数注入路由,
56 | // 从而让整个应用都有路由功能
57 | const app = new Vue({
58 | router
59 | }).$mount('#app')
60 |
61 | // 现在,应用已经启动了!
62 | ```
63 |
64 | 你可以看看这个例子
65 | [live](http://jsfiddle.net/yyx990803/xgrjzsup/)。
66 |
67 | 要注意,当 `` 对应的路由匹配成功,将自动设置 class 属性值 `.router-link-active`。查看 [API 文档](../api/router-link.md) 学习更多相关内容。
68 |
--------------------------------------------------------------------------------
/test/unit/specs/create-map.spec.js:
--------------------------------------------------------------------------------
1 | /*eslint-disable no-undef*/
2 | import { createRouteMap } from '../../../src/create-route-map'
3 |
4 | const Home = { template: 'This is Home
' }
5 | const Foo = { template: 'This is Foo
' }
6 | const Bar = { template: 'This is Bar
' }
7 | const Baz = { template: 'This is Baz
' }
8 |
9 | const routes = [
10 | { path: '/', name: 'home', component: Home },
11 | { path: '/foo', name: 'foo', component: Foo },
12 | {
13 | path: '/bar',
14 | name: 'bar',
15 | component: Bar,
16 | children: [
17 | {
18 | path: '',
19 | component: Baz,
20 | name: 'bar.baz'
21 | }
22 | ]
23 | }
24 | ]
25 |
26 | describe('Creating Route Map', function () {
27 | let maps
28 |
29 | beforeAll(function () {
30 | spyOn(console, 'warn')
31 | maps = createRouteMap(routes)
32 | })
33 |
34 | beforeEach(function () {
35 | console.warn.calls.reset()
36 | process.env.NODE_ENV = 'production'
37 | })
38 |
39 | it('has a pathMap object for default subroute at /bar/', function () {
40 | expect(maps.pathMap['/bar/']).not.toBeUndefined()
41 | })
42 |
43 | it('has a nameMap object for default subroute at \'bar.baz\'', function () {
44 | expect(maps.nameMap['bar.baz']).not.toBeUndefined()
45 | })
46 |
47 | it('in development, has logged a warning concerning named route of parent and default subroute', function () {
48 | process.env.NODE_ENV = 'development'
49 | maps = createRouteMap(routes)
50 | expect(console.warn).toHaveBeenCalled()
51 | expect(console.warn.calls.argsFor(0)[0]).toMatch('vue-router] Named Route \'bar\'')
52 | })
53 |
54 | it('in production, it has not logged this warning', function () {
55 | maps = createRouteMap(routes)
56 | expect(console.warn).not.toHaveBeenCalled()
57 | })
58 | })
59 |
--------------------------------------------------------------------------------
/docs/ru/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 | // возвращаемым значением должна быть строка или объект пути
33 | }}
34 | ]
35 | })
36 | ```
37 |
38 | Для демонстрации более сложных возможностей, обратите внимание на [этот пример](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js).
39 |
40 | ### Псевдонимы
41 |
42 | При редиректе, если пользователь переходит по пути `/a`, URL заменяется на `/b` и затем уже `/b` рассматривается как основной путь. В чём отличие псевдонима?
43 |
44 | **В случае, когда псевдонимом `/a` является `/b`, при посещении пользователем `/b` URL останется равным `/b`, но роутер выполнит все действия так, как если бы он был равен `/a`.**
45 |
46 | В виде конфигурации роутера вышесказанное может быть выражено так:
47 |
48 | ``` js
49 | const router = new VueRouter({
50 | routes: [
51 | { path: '/a', component: A, alias: '/b' }
52 | ]
53 | })
54 | ```
55 |
56 | Псевдонимы позволяют не ограничиваться вложенными структурами при организации связи URL и UI.
57 |
58 | Этот [пример](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js) демонстрирует более продвинутое использование возможностей.
59 |
--------------------------------------------------------------------------------
/docs/ru/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 | // чтобы определить, какой анимационный переход применить
49 |
50 | watch: {
51 | '$route' (to, from) {
52 | const toDepth = to.path.split('/').length
53 | const fromDepth = from.path.split('/').length
54 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
55 | }
56 | }
57 | ```
58 |
59 | Полный пример можно посмотреть [здесь](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js).
60 |
--------------------------------------------------------------------------------
/docs/zh-cn/essentials/navigation.md:
--------------------------------------------------------------------------------
1 | # 编程式的导航
2 |
3 | 除了使用 `` 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。
4 |
5 | #### `router.push(location)`
6 |
7 | 想要导航到不同的 URL,则使用 `router.push` 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。
8 |
9 | 当你点击 `` 时,这个方法会在内部调用,所以说,点击 `` 等同于调用 `router.push(...)`。
10 |
11 | | 声明式 | 编程式 |
12 | |-------------|--------------|
13 | | `` | `router.push(...)` |
14 |
15 | 该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:
16 |
17 | ``` js
18 | // 字符串
19 | router.push('home')
20 |
21 | // 对象
22 | router.push({ path: 'home' })
23 |
24 | // 命名的路由
25 | router.push({ name: 'user', params: { userId: 123 }})
26 |
27 | // 带查询参数,变成 /register?plan=private
28 | router.push({ path: 'register', query: { plan: 'private' }})
29 | ```
30 |
31 | #### `router.replace(location)`
32 |
33 | 跟 `router.push` 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
34 |
35 | | 声明式 | 编程式 |
36 | |-------------|--------------|
37 | | `` | `router.replace(...)` |
38 |
39 |
40 | #### `router.go(n)`
41 |
42 | 这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 `window.history.go(n)`。
43 |
44 | 例子
45 |
46 | ``` js
47 | // 在浏览器记录中前进一步,等同于 history.forward()
48 | router.go(1)
49 |
50 | // 后退一步记录,等同于 history.back()
51 | router.go(-1)
52 |
53 | // 前进 3 步记录
54 | router.go(3)
55 |
56 | // 如果 history 记录不够用,那就默默地失败呗
57 | router.go(-100)
58 | router.go(100)
59 | ```
60 |
61 | #### 操作 History
62 |
63 | 你也许注意到 `router.push`、 `router.replace` 和 `router.go` 跟 [`window.history.pushState`、 `window.history.replaceState` 和 `window.history.go`](https://developer.mozilla.org/en-US/docs/Web/API/History)好像, 实际上它们确实是效仿 `window.history` API 的。
64 |
65 | 因此,如果你已经熟悉 [Browser History APIs](https://developer.mozilla.org/en-US/docs/Web/API/History_API),那么在 vue-router 中操作 history 就是超级简单的。
66 |
67 | 还有值得提及的,vue-router 的导航方法 (`push`、 `replace`、 `go`) 在各类路由模式(`history`、 `hash` 和 `abstract`)下表现一致。
68 |
--------------------------------------------------------------------------------
/docs/zh-cn/api/route-object.md:
--------------------------------------------------------------------------------
1 | # 路由信息对象
2 |
3 | 一个 **route object(路由信息对象)** 表示当前激活的路由的状态信息,包含了当前 URL 解析得到的信息,还有 URL 匹配到的 **route records(路由记录)**。
4 |
5 |
6 | route object 是 immutable(不可变) 的,每次成功的导航后都会产生一个新的对象。
7 |
8 | route object 出现在多个地方:
9 |
10 | - 组件内的 `this.$route` 和 `$route` watcher 回调(监测变化处理);
11 |
12 | - `router.match(location)` 的返回值
13 |
14 | - 导航钩子的参数:
15 |
16 | ``` js
17 | router.beforeEach((to, from, next) => {
18 | // to 和 from 都是 路由信息对象
19 | })
20 | ```
21 |
22 | - `scrollBehavior` 方法的参数:
23 |
24 | ``` js
25 | const router = new VueRouter({
26 | scrollBehavior (to, from, savedPosition) {
27 | // to 和 from 都是 路由信息对象
28 | }
29 | })
30 | ```
31 |
32 | ### 路由信息对象的属性
33 |
34 | - **$route.path**
35 |
36 | - 类型: `string`
37 |
38 | 字符串,对应当前路由的路径,总是解析为绝对路径,如 `"/foo/bar"`。
39 |
40 | - **$route.params**
41 |
42 | - 类型: `Object`
43 |
44 | 一个 key/value 对象,包含了 动态片段 和 全匹配片段,如果没有路由参数,就是一个空对象。
45 |
46 | - **$route.query**
47 |
48 | - 类型: `Object`
49 |
50 | 一个 key/value 对象,表示 URL 查询参数。例如,对于路径 `/foo?user=1`,则有 `$route.query.user == 1`,如果没有查询参数,则是个空对象。
51 |
52 | - **$route.hash**
53 |
54 | - 类型: `string`
55 |
56 | 当前路由的 hash 值 (带 `#`) ,如果没有 hash 值,则为空字符串。
57 |
58 |
59 | - **$route.fullPath**
60 |
61 | - 类型: `string`
62 |
63 | 完成解析后的 URL,包含查询参数和 hash 的完整路径。
64 |
65 | - **$route.matched**
66 |
67 | - 类型: `Array`
68 |
69 | 一个数组,包含当前路由的所有嵌套路径片段的 **路由记录** 。路由记录就是 `routes` 配置数组中的对象副本(还有在 `children` 数组)。
70 |
71 | ``` js
72 | const router = new VueRouter({
73 | routes: [
74 | // 下面的对象就是 route record
75 | { path: '/foo', component: Foo,
76 | children: [
77 | // 这也是个 route record
78 | { path: 'bar', component: Bar }
79 | ]
80 | }
81 | ]
82 | })
83 | ```
84 |
85 | 当 URL 为 `/foo/bar`,`$route.matched` 将会是一个包含从上到下的所有对象(副本)。
86 |
87 | - **$route.name**
88 |
89 | 当前路由的名称,如果有的话。(查看 [命名路由](../essentials/named-routes.md))
90 |
--------------------------------------------------------------------------------
/docs/de/essentials/redirect-and-alias.md:
--------------------------------------------------------------------------------
1 | # Redirect und Alias
2 |
3 | ### Redirect (Umleitung)
4 |
5 | Ein Redirect bedeutet, dass, wenn der Nutzer `/a` besucht, die URL mit `/b` ersetzt wird und auch die Komponente der Route zu `/b` rendert. Das richtet man in der `routes`-Konfiguration folgendermaßen ein:
6 |
7 |
8 | ``` js
9 | const router = new VueRouter({
10 | routes: [
11 | { path: '/a', redirect: '/b' }
12 | ]
13 | })
14 | ```
15 |
16 | Der Redirect kann auch auf eine benannten Route angewandt werden:
17 |
18 | ``` js
19 | const router = new VueRouter({
20 | routes: [
21 | { path: '/a', redirect: { name: 'foo' }}
22 | ]
23 | })
24 | ```
25 |
26 | Oder auch mit einer Funktion für dynamische Redirects:
27 |
28 | ``` js
29 | const router = new VueRouter({
30 | routes: [
31 | { path: '/a', redirect: to => {
32 | // Die Funktion erhält die Ziel-Route als Argument
33 | // und gibt den Umleitungsort/-pfad hier aus.
34 | }}
35 | ]
36 | })
37 | ```
38 |
39 | Für erweiterte Anwendungsmöglichkeiten siehe auch dieses [Beispiel](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js).
40 |
41 | ### Alias
42 |
43 | Ein Redirect bedeutet: Wenn wir die URL `/a` besuchen, wird die URL mit `/b` ersetzt und dann mit der Route für `/b` gematched. Aber was ist dann ein *Alias*?
44 |
45 | Ein Alias von `/a` als `/b` bedeutet, dass die URL `/b` bleibt, wenn diese besucht wird, jedoch die Komponente von `/a` gerendert wird.
46 |
47 | Dieses kann man in der Router-Konfiguration folgendermaßen definieren:
48 |
49 | ``` js
50 | const router = new VueRouter({
51 | routes: [
52 | { path: '/a', component: A, alias: '/b' }
53 | ]
54 | })
55 | ```
56 |
57 | Ein Alias gibt die Möglichkeit eine bestimmte UI-Struktur einer
58 | beliebigen URL zuzuordnen, anstatt von der verschachtelten Struktur der Konfiguration eingeschränkt zu werden.
59 |
60 | Für die erweiterte Anwendung siehe folgendes [Beispiel](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js).
61 |
--------------------------------------------------------------------------------
/docs/ja/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 | // 名前付きビューによるルートに対しては、名前付きビューごとに props オプションを定義しなければなりません:
32 | {
33 | path: '/user/:id',
34 | components: { default: User, sidebar: Sidebar },
35 | props: { default: true, sidebar: false }
36 | }
37 | ]
38 | })
39 | ```
40 |
41 | これにより、コンポーネントをどこからでも使用できるようになり、コンポーネントの再利用とテストが容易になります。
42 |
43 | ### Boolean モード
44 |
45 | props を true に設定すると、route.params がコンポーネントのプロパティとして設定されます。
46 |
47 | ### Object モード
48 |
49 | props がオブジェクトの場合、これはコンポーネントプロパティとしてそのまま設定されます。
50 | プロパティが静的なときに便利です。
51 |
52 | ``` js
53 | const router = new VueRouter({
54 | routes: [
55 | { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
56 | ]
57 | })
58 | ```
59 |
60 | ### Function モード
61 |
62 | プロパティを返す関数を作成することができます。
63 | これにより、パラメータを別のタイプにキャストし、静的な値をルートベースの値などと組み合わせることができます。
64 |
65 | ``` js
66 | const router = new VueRouter({
67 | routes: [
68 | { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
69 | ]
70 | })
71 | ```
72 |
73 | url `/search?q=vue` は `{query: "vue"}` をプロパティとして SearchUser コンポーネントに渡します。
74 |
75 | ルート変更時にのみ評価されるため、props 関数はステートレスにしてください。プロパティを定義するために状態を必要とする場合はラッパーコンポーネントを使用してください。その方法で vue は状態変更に対応することができます。
76 |
77 | 高度な使い方については、[example](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js)を参照してください。
78 |
--------------------------------------------------------------------------------
/docs/zh-cn/essentials/dynamic-matching.md:
--------------------------------------------------------------------------------
1 | # 动态路由匹配
2 |
3 | 我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 `User` 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。那么,我们可以在 `vue-router` 的路由路径中使用『动态路径参数』(dynamic segment)来达到这个效果:
4 |
5 |
6 | ``` js
7 | const User = {
8 | template: 'User
'
9 | }
10 |
11 | const router = new VueRouter({
12 | routes: [
13 | // 动态路径参数 以冒号开头
14 | { path: '/user/:id', component: User }
15 | ]
16 | })
17 | ```
18 |
19 | 现在呢,像 `/user/foo` 和 `/user/bar` 都将映射到相同的路由。
20 |
21 | 一个『路径参数』使用冒号 `:` 标记。当匹配到一个路由时,参数值会被设置到
22 | `this.$route.params`,可以在每个组件内使用。于是,我们可以更新 `User` 的模板,输出当前用户的 ID:
23 |
24 | ``` js
25 | const User = {
26 | template: 'User {{ $route.params.id }}
'
27 | }
28 | ```
29 |
30 | 你可以看看这个[在线例子](http://jsfiddle.net/yyx990803/4xfa2f19/).
31 |
32 | 你可以在一个路由中设置多段『路径参数』,对应的值都会设置到 `$route.params` 中。例如:
33 |
34 | | 模式 | 匹配路径 | $route.params |
35 | |---------|------|--------|
36 | | /user/:username | /user/evan | `{ username: 'evan' }` |
37 | | /user/:username/post/:post_id | /user/evan/post/123 | `{ username: 'evan', post_id: 123 }` |
38 |
39 | 除了 `$route.params` 外,`$route` 对象还提供了其它有用的信息,例如,`$route.query`(如果 URL 中有查询参数)、`$route.hash` 等等。你可以查看 [API 文档](../api/route-object.md) 的详细说明。
40 |
41 | ### 响应路由参数的变化
42 |
43 | 提醒一下,当使用路由参数时,例如从 `/user/foo` 导航到 `user/bar`,**原来的组件实例会被复用**。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。**不过,这也意味着组件的生命周期钩子不会再被调用**。
44 |
45 | 复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch(监测变化) `$route` 对象:
46 |
47 | ``` js
48 | const User = {
49 | template: '...',
50 | watch: {
51 | '$route' (to, from) {
52 | // 对路由变化作出响应...
53 | }
54 | }
55 | }
56 | ```
57 |
58 | ### 高级匹配模式
59 |
60 | `vue-router` 使用 [path-to-regexp](https://github.com/pillarjs/path-to-regexp) 作为路径匹配引擎,所以支持很多高级的匹配模式,例如:可选的动态路径参数、匹配零个或多个、一个或多个,甚至是自定义正则匹配。查看它的 [文档](https://github.com/pillarjs/path-to-regexp#parameters) 学习高阶的路径匹配,还有 [这个例子 ](https://github.com/vuejs/vue-router/blob/next/examples/route-matching/app.js) 展示 `vue-router` 怎么使用这类匹配。
61 |
62 | ### 匹配优先级
63 |
64 | 有时候,同一个路径可以匹配多个路由,此时,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。
65 |
--------------------------------------------------------------------------------
/examples/transitions/app.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import VueRouter from 'vue-router'
3 |
4 | Vue.use(VueRouter)
5 |
6 | const Home = {
7 | template: `
8 |
12 | `
13 | }
14 |
15 | const Parent = {
16 | data () {
17 | return {
18 | transitionName: 'slide-left'
19 | }
20 | },
21 | beforeRouteUpdate (to, from, next) {
22 | const toDepth = to.path.split('/').length
23 | const fromDepth = from.path.split('/').length
24 | this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
25 | next()
26 | },
27 | template: `
28 |
29 |
Parent
30 |
31 |
32 |
33 |
34 | `
35 | }
36 |
37 | const Default = { template: 'default
' }
38 | const Foo = { template: 'foo
' }
39 | const Bar = { template: 'bar
' }
40 |
41 | const router = new VueRouter({
42 | mode: 'history',
43 | base: __dirname,
44 | routes: [
45 | { path: '/', component: Home },
46 | { path: '/parent', component: Parent,
47 | children: [
48 | { path: '', component: Default },
49 | { path: 'foo', component: Foo },
50 | { path: 'bar', component: Bar }
51 | ]
52 | }
53 | ]
54 | })
55 |
56 | new Vue({
57 | router,
58 | template: `
59 |
60 |
Transitions
61 |
62 | /
63 | /parent
64 | /parent/foo
65 | /parent/bar
66 |
67 |
68 |
69 |
70 |
71 | `
72 | }).$mount('#app')
73 |
--------------------------------------------------------------------------------
/docs/en/advanced/lazy-loading.md:
--------------------------------------------------------------------------------
1 | # Lazy Loading Routes
2 |
3 | When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each route's components into a separate chunk, and only load them when the route is visited.
4 |
5 | Combining Vue's [async component feature](http://vuejs.org/guide/components.html#Async-Components) and Webpack's [code splitting feature](https://webpack.js.org/guides/code-splitting-require/), it's trivially easy to
6 | lazy-load route components.
7 |
8 | All we need to do is define our route components as async components:
9 |
10 | ``` js
11 | const Foo = resolve => {
12 | // require.ensure is Webpack's special syntax for a code-split point.
13 | require.ensure(['./Foo.vue'], () => {
14 | resolve(require('./Foo.vue'))
15 | })
16 | }
17 | ```
18 |
19 | There's also an alternative code-split syntax using AMD style require, so this can be simplified to:
20 |
21 | ``` js
22 | const Foo = resolve => require(['./Foo.vue'], resolve)
23 | ```
24 |
25 | Nothing needs to change in the route config, just use `Foo` as usual:
26 |
27 | ``` js
28 | const router = new VueRouter({
29 | routes: [
30 | { path: '/foo', component: Foo }
31 | ]
32 | })
33 | ```
34 |
35 | ### Grouping Components in the Same Chunk
36 |
37 | Sometimes we may want to group all the components nested under the same route into the same async chunk. To achieve that we need to use [named chunks](https://webpack.js.org/guides/code-splitting-require/#chunkname) by providing a chunk name to `require.ensure` as the 3rd argument:
38 |
39 | ``` js
40 | const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
41 | const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
42 | const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
43 | ```
44 |
45 | Webpack will group any async module with the same chunk name into the same async chunk - this also means we don't need to explicitly list dependencies for `require.ensure` anymore (thus passing an empty array).
46 |
--------------------------------------------------------------------------------
/docs/en/api/options.md:
--------------------------------------------------------------------------------
1 | # Router Construction Options
2 |
3 | ### routes
4 |
5 | - type: `Array`
6 |
7 | Type declaration for `RouteConfig`:
8 |
9 | ``` js
10 | declare type RouteConfig = {
11 | path: string;
12 | component?: Component;
13 | name?: string; // for named routes
14 | components?: { [name: string]: Component }; // for named views
15 | redirect?: string | Location | Function;
16 | props?: boolean | string | Function;
17 | alias?: string | Array;
18 | children?: Array; // for nested routes
19 | beforeEnter?: (to: Route, from: Route, next: Function) => void;
20 | meta?: any;
21 | }
22 | ```
23 |
24 | ### mode
25 |
26 | - type: `string`
27 |
28 | - default: `"hash" (in browser) | "abstract" (in Node.js)`
29 |
30 | - available values: `"hash" | "history" | "abstract"`
31 |
32 | Configure the router mode.
33 |
34 | - `hash`: uses the URL hash for routing. Works in all Vue-supported browsers, including those that do not support HTML5 History API.
35 |
36 | - `history`: requires HTML5 History API and server config. See [HTML5 History Mode](../essentials/history-mode.md).
37 |
38 | - `abstract`: works in all JavaScript environments, e.g. server-side with Node.js. **The router will automatically be forced into this mode if no browser API is present.**
39 |
40 | ### base
41 |
42 | - type: `string`
43 |
44 | - default: `"/"`
45 |
46 | The base URL of the app. For example, if the entire single page application is served under `/app/`, then `base` should use the value `"/app/"`.
47 |
48 | ### linkActiveClass
49 |
50 | - type: `string`
51 |
52 | - default: `"router-link-active"`
53 |
54 | Globally configure `` default active class. Also see [router-link](router-link.md).
55 |
56 | ### scrollBehavior
57 |
58 | - type: `Function`
59 |
60 | Signature:
61 |
62 | ```
63 | (
64 | to: Route,
65 | from: Route,
66 | savedPosition?: { x: number, y: number }
67 | ) => { x: number, y: number } | { selector: string } | ?{}
68 | ```
69 |
70 | For more details see [Scroll Behavior](../advanced/scroll-behavior.md).
71 |
--------------------------------------------------------------------------------
/docs/en/advanced/scroll-behavior.md:
--------------------------------------------------------------------------------
1 | # Scroll Behavior
2 |
3 | When using client-side routing, we may want to scroll to top when navigating to a new route, or preserve the scrolling position of history entries just like real page reload does. `vue-router` allows you to achieve these and even better, allows you to completely customize the scroll behavior on route navigation.
4 |
5 | **Note: this feature only works in HTML5 history mode.**
6 |
7 | When creating the router instance, you can provide the `scrollBehavior` function:
8 |
9 | ``` js
10 | const router = new VueRouter({
11 | routes: [...],
12 | scrollBehavior (to, from, savedPosition) {
13 | // return desired position
14 | }
15 | })
16 | ```
17 |
18 | The `scrollBehavior` function receives the `to` and `from` route objects. The third argument, `savedPosition`, is only available if this is a `popstate` navigation (triggered by the browser's back/forward buttons).
19 |
20 | The function can return a scroll position object. The object could be in the form of:
21 |
22 | - `{ x: number, y: number }`
23 | - `{ selector: string }`
24 |
25 | If a falsy value or an empty object is returned, no scrolling will happen.
26 |
27 | For example:
28 |
29 | ``` js
30 | scrollBehavior (to, from, savedPosition) {
31 | return { x: 0, y: 0 }
32 | }
33 | ```
34 |
35 | This will simply make the page scroll to top for all route navigations.
36 |
37 | Returning the `savedPosition` will result in a native-like behavior when navigating with back/forward buttons:
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 | If you want to simulate the "scroll to anchor" behavior:
50 |
51 | ``` js
52 | scrollBehavior (to, from, savedPosition) {
53 | if (to.hash) {
54 | return {
55 | selector: to.hash
56 | }
57 | }
58 | }
59 | ```
60 |
61 | We can also use [route meta fields](meta.md) to implement fine-grained scroll behavior control. Check out a full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/scroll-behavior/app.js).
62 |
--------------------------------------------------------------------------------
/docs/de/api/options.md:
--------------------------------------------------------------------------------
1 | # Optionen des Router-Konstruktors
2 |
3 | ### routes
4 |
5 | - Typ: `Array`
6 |
7 | Typendeklaration für `RouteConfig`:
8 |
9 | ``` js
10 | declare type RouteConfig = {
11 | path: string;
12 | component?: Component;
13 | name?: string; // für benannte Routes
14 | components?: { [name: string]: Component }; // für benannte Views
15 | redirect?: string | Location | Function;
16 | alias?: string | Array;
17 | children?: Array; // für Verschachtelte Routes
18 | beforeEnter?: (to: Route, from: Route, next: Function) => void;
19 | meta?: any;
20 | }
21 | ```
22 |
23 | ### mode
24 |
25 | - Typ: `string`
26 |
27 | - Default: `"hash" (in browser) | "abstract" (in Node.js)`
28 |
29 | - verfügbare Werte: `"hash" | "history" | "abstract"`
30 |
31 | Bestimmt den Router-Mode.
32 |
33 | - `hash`: Nutzt den URL-Hash für das Routing. Funktioniert in allen Vue-unterstützten Browsern, inklusive derer, die HTML5 Verlaufs-API nicht unterstützen.
34 |
35 | - `history`: Benötigt HTML5 Verlaufs-API und Serverkonfiguration. Siehe [HTML5 Verlaufsmodus](../essentials/history-mode.md).
36 |
37 | - `abstract`: Funktioniert in jeder JavaScript-Umgebung, zB. serverseitig mit Node.js. **Der Router wird automatisch in diesen Modus gezwungen, wenn keine Browser-API vorhanden ist.**
38 |
39 | ### base
40 |
41 | - Typ: `string`
42 |
43 | - Default: `"/"`
44 |
45 | Die Basis-URL der App. Läuft zum Beispiel die gesamte Single-Page-Applikation unter `/app`, sollte `base` den Wert `"/app"` haben.
46 |
47 | ### linkActiveClass
48 |
49 | - Typ: `string`
50 |
51 | - Default: `"router-link-active"`
52 |
53 | Definiert global den Namen der "active" Klasse für ``. Siehe auch [router-link](router-link.md).
54 |
55 | ### scrollBehavior
56 |
57 | - Typ: `Function`
58 |
59 | Signatur:
60 |
61 | ```
62 | (
63 | to: Route,
64 | from: Route,
65 | savedPosition?: { x: number, y: number }
66 | ) => { x: number, y: number } | { selector: string } | ?{}
67 | ```
68 |
69 | Für mehr Details siehe [Scroll-Verhalten](../advanced/scroll-behavior.md).
70 |
--------------------------------------------------------------------------------
/docs/ja/api/route-object.md:
--------------------------------------------------------------------------------
1 | # ルートオブジェクト
2 |
3 | **ルートオブジェクト**は現在のアクティブなルートの状態を表現しています。現在の URL をパースした情報と、その URL とマッチした**ルートレコード**を保持しています。
4 |
5 | ルートオブジェクトは変更不可です。成功した全てのナビゲーションは結果的に新たなルートオブジェクトになります。
6 |
7 | ルートオブジェクトは複数の場所に存在します。
8 |
9 | - コンポーネント内での `this.$route`、また、 `$route` watcher コールバック内部。
10 |
11 | - `router.match(location)` を呼び出した時の返り値。
12 |
13 | - ナビゲーションガード内での第 1 引数、第 2 引数として:
14 |
15 | ``` js
16 | router.beforeEach((route, redirect, next) => {
17 | // ここの route はルートオブジェクト
18 | })
19 | ```
20 |
21 | - `scrollBehavior` 関数内の第 1 引数、第 2 引数として:
22 |
23 | ``` js
24 | const router = new VueRouter({
25 | scrollBehavior (to, from, savedPosition) {
26 | // to と from は両方ともルートオブジェクト
27 | }
28 | })
29 | ```
30 |
31 | ### ルートオブジェクトプロパティ
32 |
33 | - **$route.path**
34 |
35 | - 型: `string`
36 |
37 | 現在のルートのパスに等しい文字列。常に絶対パスとして解釈されます。e.g. `"/foo/bar"`
38 |
39 | - **$route.params**
40 |
41 | - 型: `Object`
42 |
43 | 動的セグメントとスターセグメントの key/value ペアを保持するオブジェクト。もしパラメーターがない場合、この値は空オブジェクトになります。
44 |
45 | - **$route.query**
46 |
47 | - 型: `Object`
48 |
49 | クエリ文字列の key/value ペアを保持するオブジェクト。例えば `/foo?user=1` というパスの場合、`$route.query.user == 1` となります。もしクエリがない場合は、この値は空オブジェクトになります。
50 |
51 | - **$route.hash**
52 |
53 | - 型: `string`
54 |
55 | hash がある時の現在のルートの hash (# 有り) です。もし hash がない場合、この値は空オブジェクトになります。
56 |
57 | - **$route.fullPath**
58 |
59 | - 型: `string`
60 |
61 | クエリや hash を含む完全に解決された URL です。
62 |
63 | - **$route.matched**
64 |
65 | - 型: `Array`
66 |
67 | 現在のルートのネストされた全パスセグメントに対しての**ルートレコード** を保持している配列です。ルートレコードは `routes` 設定の配列 (と `children` 配列) 内のオブジェクトのコピーです。
68 |
69 | ``` js
70 | const router = new VueRouter({
71 | routes: [
72 | // 以下のオブジェクトがルートレコード
73 | { path: '/foo', component: Foo,
74 | children: [
75 | // こちらもルートレコード
76 | { path: 'bar', component: Bar }
77 | ]
78 | }
79 | ]
80 | })
81 | ```
82 |
83 | URL が `/foo/bar` である時、 `$route.matched` は親から子の順番で両方の (クローンされた) オブジェクトを含む配列になります。
84 |
85 | - **$route.name**
86 |
87 | 名前がある場合の現在のルートの名前です。(詳しくは [名前付きルート](../essentials/named-routes.md) をご参照ください)
88 |
--------------------------------------------------------------------------------
/docs/kr/api/route-object.md:
--------------------------------------------------------------------------------
1 | # 라우트 객체
2 |
3 | **라우트 객체** 는 현재 활성 경로의 상태를 나타냅니다. 여기에는 현재 URL의 구문 분석 된 정보와 URL에서 일치하는 **라우트 기록** 이 포함됩니다.
4 |
5 | route 객체는 변경할 수 없습니다. 모든 성공적인 네비게이션은 새로운 라우트 객체를 생성합니다.
6 |
7 | 라우트 객체는 여러 위치에서 찾을 수 있습니다.
8 |
9 | - 컴포넌트 내부에서 `this.$route`를 사용합니다.
10 |
11 | - 감시자 콜백에서 `$route`를 사용합니다.
12 |
13 | - `router.match(location)` 호출의 반환 값으로 사용합니다.
14 |
15 | - 처음 두 개의 전달인자로 내비게이션 가드에서 사용할 수 있습니다.
16 |
17 | ``` js
18 | router.beforeEach((to, from, next) => {
19 | // to와 from은 둘 다 라우트 객체입니다.
20 | })
21 | ```
22 |
23 | - `scrollBehavior`함수 안에서 처음 두 개의 전달인자로 사용합니다.
24 |
25 | ``` js
26 | const router = new VueRouter({
27 | scrollBehavior (to, from, savedPosition) {
28 | // to와 from은 둘 다 라우트 객체입니다.
29 | }
30 | })
31 | ```
32 |
33 | ### 라우트 객체 속성
34 |
35 | - **$route.path**
36 |
37 | - 자료형: `string`
38 |
39 | 현재 경로의 경로와 동일한 문자열로 항상 절대 경로로 해석됩니다. 예 : `"/foo/bar"`를 사용하십시오.
40 |
41 | - **$route.params**
42 |
43 | - 자료형: `Object`
44 |
45 | 동적 세그먼트와 별 세그먼트의 키/값 쌍을 포함하는 객체입니다. 매개 변수가 없는 경우 값은 빈 객체가됩니다.
46 |
47 | - **$route.query**
48 |
49 | - 자료형: `Object`
50 |
51 | 쿼리 문자열의 키/값 쌍을 포함하는 객체입니다. 예를 들어 `/foo?user=1` 경로의 경우 `$route.query.user == 1`을 얻습니다. 쿼리가 없으면 값은 빈 객체가됩니다.
52 |
53 | - **$route.hash**
54 |
55 | - 자료형: `string`
56 |
57 | 현재 경로의 해시(`#`가 없는 경우).해시가 존재하지 않으면 값은 빈 문자열이됩니다.
58 |
59 | - **$route.fullPath**
60 |
61 | - 자료형: `string`
62 |
63 | 쿼리 및 해시를 포함한 전체 URL입니다.
64 |
65 | - **$route.matched**
66 |
67 | - 자료형: `Array`
68 |
69 | 현재 라우트의 모든 중첩 된 라우트 세그먼트에 대해 **라우트 레코드** 가 포함 된 배열입니다. 라우트 레코드는 `routes` 배열(그리고 `children` 배열)에 있는 객체의 복사본입니다.
70 |
71 | ``` js
72 | const router = new VueRouter({
73 | routes: [
74 | // 다음 객체는 라우트 레코드입니다.
75 | { path: '/foo', component: Foo,
76 | children: [
77 | // 이 또한 라우트 레코드입니다.
78 | { path: 'bar', component: Bar }
79 | ]
80 | }
81 | ]
82 | })
83 | ```
84 |
85 | URL이 `/foo/bar` 인 경우, `$route.matched`는 두 객체(복제 된 객체)를 자식 배열에 포함하는 배열입니다.
86 |
87 | - **$route.name**
88 |
89 | 현재 라우트의 이름입니다.(가지고 있는 경우). [이름을 가진](../essentials/named-routes.md)를 확인하세요
90 |
--------------------------------------------------------------------------------
/examples/route-matching/app.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import VueRouter from 'vue-router'
3 |
4 | Vue.use(VueRouter)
5 |
6 | // The matching uses path-to-regexp, which is the matching engine used
7 | // by express as well, so the same matching rules apply.
8 | // For detailed rules, see https://github.com/pillarjs/path-to-regexp
9 | const router = new VueRouter({
10 | mode: 'history',
11 | base: __dirname,
12 | routes: [
13 | { path: '/' },
14 | // params are denoted with a colon ":"
15 | { path: '/params/:foo/:bar' },
16 | // a param can be made optional by adding "?"
17 | { path: '/optional-params/:foo?' },
18 | // a param can be followed by a regex pattern in parens
19 | // this route will only be matched if :id is all numbers
20 | { path: '/params-with-regex/:id(\\d+)' },
21 | // asterisk can match anything
22 | { path: '/asterisk/*' },
23 | // make part of the path optional by wrapping with parens and add "?"
24 | { path: '/optional-group/(foo/)?bar' }
25 | ]
26 | })
27 |
28 | new Vue({
29 | router,
30 | template: `
31 |
32 |
Route Matching
33 |
34 | /
35 | /params/foo/bar
36 | /optional-params
37 | /optional-params/foo
38 | /params-with-regex/123
39 | /params-with-regex/abc
40 | /asterisk/foo
41 | /asterisk/foo/bar
42 | /optional-group/bar
43 | /optional-group/foo/bar
44 |
45 |
Route context
46 |
{{ JSON.stringify($route, null, 2) }}
47 |
48 | `
49 | }).$mount('#app')
50 |
--------------------------------------------------------------------------------
/docs/en/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # Router Instance
2 |
3 | ### Properties
4 |
5 | #### router.app
6 |
7 | - type: `Vue instance`
8 |
9 | The root Vue instance the `router` was injected into.
10 |
11 | #### router.mode
12 |
13 | - type: `string`
14 |
15 | The [mode](options.md#mode) the router is using.
16 |
17 | #### router.currentRoute
18 |
19 | - type: `Route`
20 |
21 | The current route represented as a [Route Object](route-object.md).
22 |
23 | ### Methods
24 |
25 | - **router.beforeEach(guard)**
26 | - **router.afterEach(hook)**
27 |
28 | Add global navigation guards. See [Navigation Guards](../advanced/navigation-guards.md).
29 |
30 |
31 | - **router.push(location, onComplete?, onAbort?)**
32 | - **router.replace(location, onComplete?, onAbort?)**
33 | - **router.go(n)**
34 | - **router.back()**
35 | - **router.forward()**
36 |
37 | Programmatically navigate to a new URL. See [Programmatic Navigation](../essentials/navigation.md).
38 |
39 | - **router.getMatchedComponents(location?)**
40 |
41 | Returns an Array of the components (definition/constructor, not instances) matched by the provided location or the current route. This is mostly used during server-side rendering to perform data prefetching.
42 |
43 | - **router.resolve(location, current?, append?)**
44 |
45 | > 2.1.0+
46 |
47 | Reverse URL resolving. Given location in form same as used in ` `, returns object with the following resolved properties:
48 |
49 | ``` js
50 | {
51 | location: Location;
52 | route: Route;
53 | href: string;
54 | }
55 | ```
56 |
57 | - **router.addRoutes(routes)**
58 |
59 | > 2.2.0+
60 |
61 | Dynamically add more routes to the router. The argument must be an Array using the same route config format with the `routes` constructor option.
62 |
63 | - **router.onReady(callback)**
64 |
65 | > 2.2.0+
66 |
67 | This method queues a callback to be called when the router has completed the initial navigation, which means it has resolved all async enter hooks and async components that are associated with the initial route.
68 |
69 | This is useful in server-side rendering to ensure consistent output on both the server and the client.
70 |
--------------------------------------------------------------------------------
/docs/ru/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # Инстанс Router'а
2 |
3 | ### Свойства
4 |
5 | #### router.app
6 |
7 | - тип: `Vue instance`
8 |
9 | Корневой инстанс Vue, в который был интегрирован `router`.
10 |
11 | #### router.mode
12 |
13 | - тип: `string`
14 |
15 | [Режим](options.md#mode), используемый роутером.
16 |
17 | #### router.currentRoute
18 |
19 | - тип: `Route`
20 |
21 | Текущий путь в виде [объекта Route](route-object.md).
22 |
23 | ### Методы
24 |
25 | - **router.beforeEach(guard)**
26 | - **router.afterEach(hook)**
27 |
28 | См. [сторожевые хуки](../advanced/navigation-guards.md).
29 |
30 |
31 | - **router.push(location, onComplete?, onAbort?)**
32 | - **router.replace(location, onComplete?, onAbort?)**
33 | - **router.go(n)**
34 | - **router.back()**
35 | - **router.forward()**
36 |
37 | Методы для императивного перехода к новому URL. См. [Императивная навигация](../essentials/navigation.md).
38 |
39 | - **router.getMatchedComponents(location?)**
40 |
41 | Возвращает массив компонентов (определение/конструктор, не инстансы), совпадающих с текущим путём. В основном используется во время рендеринга на сервере для получения необходимых данных.
42 |
43 | - **router.resolve(location, current?, append?)**
44 |
45 | > 2.1.0+
46 |
47 | Служит для обратного разрешения URL. Получая на вход путь в том же формате, что используется ` `, возвращает объект со следующими свойствами:
48 |
49 | ``` js
50 | {
51 | location: Location;
52 | route: Route;
53 | href: string;
54 | }
55 | ```
56 |
57 | - **router.addRoutes(routes)**
58 |
59 | > 2.2.0+
60 |
61 | Динамически добавить дополнительные маршруты в маршрутизатор. Аргументом должен быть массив маршрутов в таком же формате как и в опции `routes` конструктора.
62 |
63 | - **router.onReady(callback)**
64 |
65 | > 2.2.0+
66 |
67 | Этот метод добавляет в очередь коллбек, который будет вызван когда маршрутизатор завершит начальную навигацию, что означает что будут завершены все асинхронные хуки и будут готовы асинхронные компоненты связанные с начальным маршрутом.
68 |
69 | Это будет полезно при рендеринге на стороне сервера для обеспечения одинакового результата как на сервере, так и на клиенте.
70 |
--------------------------------------------------------------------------------
/examples/scroll-behavior/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 = { template: 'foo
' }
8 | const Bar = {
9 | template: `
10 |
11 | bar
12 |
13 |
Anchor
14 |
15 | `
16 | }
17 |
18 | // scrollBehavior:
19 | // - only available in html5 history mode
20 | // - defaults to no scroll behavior
21 | // - return false to prevent scroll
22 | const scrollBehavior = (to, from, savedPosition) => {
23 | if (savedPosition) {
24 | // savedPosition is only available for popstate navigations.
25 | return savedPosition
26 | } else {
27 | const position = {}
28 | // new navigation.
29 | // scroll to anchor by returning the selector
30 | if (to.hash) {
31 | position.selector = to.hash
32 | }
33 | // check if any matched route config has meta that requires scrolling to top
34 | if (to.matched.some(m => m.meta.scrollToTop)) {
35 | // cords will be used if no selector is provided,
36 | // or if the selector didn't match any element.
37 | position.x = 0
38 | position.y = 0
39 | }
40 | // if the returned position is falsy or an empty object,
41 | // will retain current scroll position.
42 | return position
43 | }
44 | }
45 |
46 | const router = new VueRouter({
47 | mode: 'history',
48 | base: __dirname,
49 | scrollBehavior,
50 | routes: [
51 | { path: '/', component: Home, meta: { scrollToTop: true }},
52 | { path: '/foo', component: Foo },
53 | { path: '/bar', component: Bar, meta: { scrollToTop: true }}
54 | ]
55 | })
56 |
57 | new Vue({
58 | router,
59 | template: `
60 |
61 |
Scroll Behavior
62 |
63 | /
64 | /foo
65 | /bar
66 | /bar#anchor
67 |
68 |
69 |
70 | `
71 | }).$mount('#app')
72 |
--------------------------------------------------------------------------------
/flow/declarations.js:
--------------------------------------------------------------------------------
1 | declare var document: Document;
2 |
3 | declare module 'path-to-regexp' {
4 | declare var exports: {
5 | (path: string, keys: Array{ name: string }>): RegExp;
6 | compile: (path: string) => (params: Object) => string;
7 | }
8 | }
9 |
10 | declare type Dictionary = { [key: string]: T }
11 |
12 | declare type NavigationGuard = (
13 | to: Route,
14 | from: Route,
15 | next: (to?: RawLocation | false | Function | void) => void
16 | ) => any
17 |
18 | declare type RouterOptions = {
19 | routes?: Array;
20 | mode?: string;
21 | base?: string;
22 | linkActiveClass?: string;
23 | scrollBehavior?: (
24 | to: Route,
25 | from: Route,
26 | savedPosition: ?{ x: number, y: number }
27 | ) => { x: number, y: number } | { selector: string } | ?{};
28 | }
29 |
30 | declare type RedirectOption = RawLocation | ((to: Route) => RawLocation)
31 |
32 | declare type RouteConfig = {
33 | path: string;
34 | name?: string;
35 | component?: any;
36 | components?: Dictionary;
37 | redirect?: RedirectOption;
38 | alias?: string | Array;
39 | children?: Array;
40 | beforeEnter?: NavigationGuard;
41 | meta?: any;
42 | props?: boolean | Object | Function;
43 | }
44 |
45 | declare type RouteRecord = {
46 | path: string;
47 | components: Dictionary;
48 | instances: Dictionary;
49 | name: ?string;
50 | parent: ?RouteRecord;
51 | redirect: ?RedirectOption;
52 | matchAs: ?string;
53 | beforeEnter: ?NavigationGuard;
54 | meta: any;
55 | props: boolean | Object | Function | Dictionary;
56 | }
57 |
58 | declare type Location = {
59 | _normalized?: boolean;
60 | name?: string;
61 | path?: string;
62 | hash?: string;
63 | query?: Dictionary;
64 | params?: Dictionary;
65 | append?: boolean;
66 | replace?: boolean;
67 | }
68 |
69 | declare type RawLocation = string | Location
70 |
71 | declare type Route = {
72 | path: string;
73 | name: ?string;
74 | hash: string;
75 | query: Dictionary;
76 | params: Dictionary;
77 | fullPath: string;
78 | matched: Array;
79 | redirectedFrom?: string;
80 | meta?: any;
81 | }
82 |
--------------------------------------------------------------------------------
/docs/kr/essentials/getting-started.md:
--------------------------------------------------------------------------------
1 | # 시작하기
2 |
3 | > 가이드의 샘플 코드는[ES2015](https://github.com/lukehoban/es6features)를 사용합니다.
4 |
5 | Vue.js와 vue-router로 단일 페이지 애플리케이션을 만드는 것은 간단합니다. Vue.js를 통해 우리는 이미 컴포넌트로 애플리케이션을 구성하고 있습니다. vue-router를 추가 할 때, 우리가해야 할 일은 우리의 컴포넌트를 route에 매핑하고 vue-router가 어디서 렌더링할 지 지정하는 것입니다. 다음은 기본적인 예입니다.
6 |
7 | > 모든 예제는 Vue의 독립형 버전을 사용하여 템플릿 구문 분석을 가능하게합니다. 자세한 내용은 [여기](http://vuejs.org/guide/installation.html#Standalone-vs-Runtime-only-Build) 있습니다.
8 |
9 | ### HTML
10 |
11 | ``` html
12 |
13 |
14 |
15 |
16 |
Hello App!
17 |
18 |
19 |
20 |
21 | Go to Foo
22 | Go to Bar
23 |
24 |
25 |
26 |
27 |
28 | ```
29 |
30 | ### JavaScript
31 |
32 | ``` js
33 | // 0. 모듈 시스템을 사용하는 경우 (예: vue-cli를 이용해서), Vue 및 VueRouter를 가져온 다음 Vue.use(VueRouter)를 호출하십시오.
34 |
35 | // 1. 라우트 컴포넌트를 정의하십시오.
36 | // 다른 파일에서 가져올 수 있습니다.
37 | const Foo = { template: 'foo
' }
38 | const Bar = { template: 'bar
' }
39 |
40 | // 2. 라우트를 정의합니다.
41 | // 일부 라우트 정의 각 라우트는 컴포넌트에 맵핑되어야합니다.
42 | // "컴포넌트"는 Vue.extend()를 통해 생성된
43 | // 실제 컴포넌트 생성자이거나 컴포넌트 옵션 객체 일 수 있습니다.
44 | // 나중에 중첩 된 라우트에 대해 이야기하겠습니다.
45 | const routes = [
46 | { path: '/foo', component: Foo },
47 | { path: '/bar', component: Bar }
48 | ]
49 |
50 | // 3. 라우터 인스턴스를 생성하고 `routes` 옵션을 전달하십시오.
51 | // 여기에 추가 옵션을 전달할 수 있지만, 지금은 간단하게 하겠습니다.
52 | const router = new VueRouter({
53 | routes // routes: routes 의 약어
54 | })
55 |
56 | // 4. 루트 인스턴스를 만들고 마운트하십시오.
57 | // 라우터 옵션을 라우터에 삽입하여
58 | // 전체 응용 프로그램을 라우터가 인식하도록 하십시오.
59 | const app = new Vue({
60 | router
61 | }).$mount('#app')
62 |
63 | // 이제 앱을 시작 해보세요!
64 | ```
65 |
66 | 이 [예제](http://jsfiddle.net/yyx990803/xgrjzsup/)를 확인하십시오.
67 |
68 | ``는 가리키는 라우트가 일치 할 때 자동으로 `.router-link-active` 클래스를 얻습니다. API 레퍼런스에서 더 많은 것을 배울 수 있습니다.
69 |
--------------------------------------------------------------------------------
/src/history/html5.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import type Router from '../index'
4 | import { History } from './base'
5 | import { cleanPath } from '../util/path'
6 | import { setupScroll, handleScroll } from '../util/scroll'
7 | import { pushState, replaceState } from '../util/push-state'
8 |
9 | export class HTML5History extends History {
10 | constructor (router: Router, base: ?string) {
11 | super(router, base)
12 |
13 | const expectScroll = router.options.scrollBehavior
14 |
15 | if (expectScroll) {
16 | setupScroll()
17 | }
18 |
19 | window.addEventListener('popstate', e => {
20 | this.transitionTo(getLocation(this.base), route => {
21 | if (expectScroll) {
22 | handleScroll(router, route, this.current, true)
23 | }
24 | })
25 | })
26 | }
27 |
28 | go (n: number) {
29 | window.history.go(n)
30 | }
31 |
32 | push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
33 | const { current: fromRoute } = this
34 | this.transitionTo(location, route => {
35 | pushState(cleanPath(this.base + route.fullPath))
36 | handleScroll(this.router, route, fromRoute, false)
37 | onComplete && onComplete(route)
38 | }, onAbort)
39 | }
40 |
41 | replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
42 | const { current: fromRoute } = this
43 | this.transitionTo(location, route => {
44 | replaceState(cleanPath(this.base + route.fullPath))
45 | handleScroll(this.router, route, fromRoute, false)
46 | onComplete && onComplete(route)
47 | }, onAbort)
48 | }
49 |
50 | ensureURL (push?: boolean) {
51 | if (getLocation(this.base) !== this.current.fullPath) {
52 | const current = cleanPath(this.base + this.current.fullPath)
53 | push ? pushState(current) : replaceState(current)
54 | }
55 | }
56 |
57 | getCurrentLocation (): string {
58 | return getLocation(this.base)
59 | }
60 | }
61 |
62 | export function getLocation (base: string): string {
63 | let path = window.location.pathname
64 | if (base && path.indexOf(base) === 0) {
65 | path = path.slice(base.length)
66 | }
67 | return (path || '/') + window.location.search + window.location.hash
68 | }
69 |
--------------------------------------------------------------------------------
/test/e2e/specs/active-links.js:
--------------------------------------------------------------------------------
1 |
2 | module.exports = {
3 | 'active links': function (browser) {
4 | browser
5 | .url('http://localhost:8080/active-links/')
6 | .waitForElementVisible('#app', 1000)
7 | .assert.count('li a', 11)
8 | // assert correct href with base
9 | .assert.attributeContains('li:nth-child(1) a', 'href', '/active-links/')
10 | .assert.attributeContains('li:nth-child(2) a', 'href', '/active-links/')
11 | .assert.attributeContains('li:nth-child(3) a', 'href', '/active-links/users')
12 | .assert.attributeContains('li:nth-child(4) a', 'href', '/active-links/users')
13 | .assert.attributeContains('li:nth-child(5) a', 'href', '/active-links/users/evan')
14 | .assert.attributeContains('li:nth-child(6) a', 'href', '/active-links/users/evan#foo')
15 | .assert.attributeContains('li:nth-child(7) a', 'href', '/active-links/users/evan?foo=bar')
16 | .assert.attributeContains('li:nth-child(8) a', 'href', '/active-links/users/evan?foo=bar')
17 | .assert.attributeContains('li:nth-child(9) a', 'href', '/active-links/users/evan?foo=bar&baz=qux')
18 | .assert.attributeContains('li:nth-child(10) a', 'href', '/active-links/about')
19 | .assert.attributeContains('li:nth-child(11) a', 'href', '/active-links/about')
20 | .assert.containsText('.view', 'Home')
21 |
22 | assertActiveLinks(1, [1, 2])
23 | assertActiveLinks(2, [1, 2])
24 | assertActiveLinks(3, [1, 3, 4])
25 | assertActiveLinks(4, [1, 3, 4])
26 | assertActiveLinks(5, [1, 3, 5])
27 | assertActiveLinks(6, [1, 3, 5, 6])
28 | assertActiveLinks(7, [1, 3, 5, 7, 8])
29 | assertActiveLinks(8, [1, 3, 5, 7, 8])
30 | assertActiveLinks(9, [1, 3, 5, 7, 9])
31 | assertActiveLinks(10, [1, 10], [11])
32 | assertActiveLinks(11, [1, 10], [11])
33 |
34 | browser.end()
35 |
36 | function assertActiveLinks (n, activeA, activeLI) {
37 | browser.click(`li:nth-child(${n}) a`)
38 | activeA.forEach(i => {
39 | browser.assert.cssClassPresent(`li:nth-child(${i}) a`, 'router-link-active')
40 | })
41 | activeLI && activeLI.forEach(i => {
42 | browser.assert.cssClassPresent(`li:nth-child(${i})`, 'router-link-active')
43 | })
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/docs/de/api/router-instance.md:
--------------------------------------------------------------------------------
1 | # Router-Instanz
2 |
3 | ### Eigenschaften
4 |
5 | #### router.app
6 |
7 | - Typ: `Vue instance`
8 |
9 | Die grundlegende Vue-Instanz, in die `router` injiziert wurde.
10 |
11 | #### router.mode
12 |
13 | - Typ: `string`
14 |
15 | Der [Modus](options.md#mode), den der Router nutzt.
16 |
17 |
18 | #### router.currentRoute
19 |
20 | - Typ: `Route`
21 |
22 | Die akuelle Route wiedergespiegelt als [Route-Objekt](route-object.md).
23 |
24 | ### Methoden
25 |
26 | - **router.beforeEach(guard)**
27 | - **router.afterEach(hook)**
28 |
29 | Füge globalen Navigationsschutz hinzu. Siehe [Navigations-Guards](../advanced/navigation-guards.md).
30 |
31 |
32 | - **router.push(location)**
33 | - **router.replace(location)**
34 | - **router.go(n)**
35 | - **router.back()**
36 | - **router.forward()**
37 |
38 | Navigiere programmatisch zu einer neuen URL. Siehe [Programmatische Navigation](../essentials/navigation.md).
39 |
40 | - **router.getMatchedComponents(location?)**
41 |
42 | Gibt einen Array von Komponenten (Definition/Konstruktor, nicht Instanz) zurück, die für den gegebenen Ort oder die aktuelle Route gematched wurden. Wird meist bei serverseitigem Rendern genutzt, um ein Vor-Laden von Daten zu ermöglichen.
43 |
44 | - **router.resolve(location, current?, append?)**
45 |
46 | Umgekehrte URL-Erkennung. Wenn man einZiel in gleicher Form wie in `` übergibt, gibt die Funktion ein Objekt mit den folgenden Eigenschaften zurück:
47 |
48 | ``` js
49 | {
50 | location: Location;
51 | route: Route;
52 | href: string;
53 | }
54 | ```
55 |
56 | - **router.addRoutes(routes)**
57 |
58 | > 2.2.0+
59 |
60 | Füge dynamisch weitere Routes zum Router hinzu. Das Argument must be an Array mit dem gleichen Format wie die `routes` Konstruktor-Option sein.
61 |
62 | - **router.onReady(callback)**
63 |
64 | > 2.2.0+
65 |
66 | Diese Methode queued eine Callback-Funktion, welche aufgerufen wird sobald der router die initiale Navigation beendet hat - das heißt, dass alle asynchronen Komponenten und enter-hooks, die zu der aktuellen Route gehören geladen und ausgeführt wurden.
67 |
68 | Damit kann man im serverseitigen Rendern sicherstellen, dass auf dem Server und im Client der gleiche Output gerendert wird.
69 |
--------------------------------------------------------------------------------
/docs/ja/essentials/getting-started.md:
--------------------------------------------------------------------------------
1 | # はじめに
2 |
3 | > ガイド内のコードのサンプルは [ES2015](https://github.com/lukehoban/es6features) を使っています。
4 |
5 | Vue.js と vue-router を使ったシングルページアプリケーションの構築は驚くほど簡単です。Vue.js のコンポーネントを使ってアプリケーションを既に構成しています。vue-router を混ぜ込むには、コンポーネントとルートをマッピングさせて vue-router にどこでレンダリングするかを知らせるだけです。以下が基本的な例です。
6 |
7 | > すべての example では、vue のスタンドアロンバージョンを使用してテンプレートを解析可能にしています。詳細は[こちら](http://jp.vuejs.org/v2/guide/installation.html#スタンドアロン-vs-ランタイム限定ビルド)を参照してください。
8 |
9 | ### HTML
10 |
11 | ``` html
12 |
13 |
14 |
15 |
16 |
Hello App!
17 |
18 |
19 |
20 |
21 | Go to Foo
22 | Go to Bar
23 |
24 |
25 |
26 |
27 |
28 | ```
29 |
30 | ### JavaScript
31 |
32 | ``` js
33 | // 0. モジュールシステムを使っている場合 (例: vue-clie 経由で)、Vue と VueRouter をインポートし、Vue.use(VueRouter) を呼び出します。
34 |
35 | // 1. ルートコンポーネントを定義します
36 | // 他のファイルからインポートすることもできます
37 | const Foo = { template: 'foo
' }
38 | const Bar = { template: 'bar
' }
39 |
40 | // 2. ルートをいくつか定義します
41 | // 各ルートは 1 つのコンポーネントとマッピングされる必要があります。
42 | // このコンポーネントは実際の Vue.extend()、
43 | // またはコンポーネントオプションのオブジェクトでも構いません。
44 | // ネストされたルートに関しては後で説明します
45 | const routes = [
46 | { path: '/foo', component: Foo },
47 | { path: '/bar', component: Bar }
48 | ]
49 |
50 | // 3. ルーターインスタンスを作成して、ルートオプションを渡します
51 | // 追加のオプションをここで指定できますが、
52 | // この例ではシンプルにしましょう
53 | const router = new VueRouter({
54 | routes // routes: routes の短縮表記
55 | })
56 |
57 | // 4. root となるインスタンスを作成してマウントします
58 | // アプリケーション全体がルーターを認知できるように、
59 | // ルーターをインジェクトすることを忘れないでください。
60 | const app = new Vue({
61 | router
62 | }).$mount('#app')
63 |
64 | // これで開始です!
65 | ```
66 |
67 | [動作](http://jsfiddle.net/yyx990803/xgrjzsup/) の例も確認してみてください.
68 |
69 | `` は対象のルートがマッチした時に自動的に `.router-link-active` が付与されるのにお気づきでしょうか。
70 | より詳細については [API リファレンス](../api/router-link.md) をご参照ください。
71 |
--------------------------------------------------------------------------------
/test/unit/specs/path.spec.js:
--------------------------------------------------------------------------------
1 | import { resolvePath, parsePath, cleanPath } from '../../../src/util/path'
2 |
3 | describe('Path utils', () => {
4 | describe('resolvePath', () => {
5 | it('absolute', () => {
6 | const path = resolvePath('/a', '/b')
7 | expect(path).toBe('/a')
8 | })
9 |
10 | it('relative', () => {
11 | const path = resolvePath('c/d', '/b')
12 | expect(path).toBe('/c/d')
13 | })
14 |
15 | it('relative with append', () => {
16 | const path = resolvePath('c/d', '/b', true)
17 | expect(path).toBe('/b/c/d')
18 | })
19 |
20 | it('relative parent', () => {
21 | const path = resolvePath('../d', '/a/b/c')
22 | expect(path).toBe('/a/d')
23 | })
24 |
25 | it('relative parent with append', () => {
26 | const path = resolvePath('../d', '/a/b/c', true)
27 | expect(path).toBe('/a/b/d')
28 | })
29 |
30 | it('relative query', () => {
31 | const path = resolvePath('?foo=bar', '/a/b')
32 | expect(path).toBe('/a/b?foo=bar')
33 | })
34 |
35 | it('relative hash', () => {
36 | const path = resolvePath('#hi', '/a/b')
37 | expect(path).toBe('/a/b#hi')
38 | })
39 | })
40 |
41 | describe('parsePath', () => {
42 | it('plain', () => {
43 | const res = parsePath('/a')
44 | expect(res.path).toBe('/a')
45 | expect(res.hash).toBe('')
46 | expect(res.query).toBe('')
47 | })
48 |
49 | it('query', () => {
50 | const res = parsePath('/a?foo=bar???')
51 | expect(res.path).toBe('/a')
52 | expect(res.hash).toBe('')
53 | expect(res.query).toBe('foo=bar???')
54 | })
55 |
56 | it('hash', () => {
57 | const res = parsePath('/a#haha#hoho')
58 | expect(res.path).toBe('/a')
59 | expect(res.hash).toBe('#haha#hoho')
60 | expect(res.query).toBe('')
61 | })
62 |
63 | it('both', () => {
64 | const res = parsePath('/a?foo=bar#ok?baz=qux')
65 | expect(res.path).toBe('/a')
66 | expect(res.hash).toBe('#ok?baz=qux')
67 | expect(res.query).toBe('foo=bar')
68 | })
69 | })
70 |
71 | describe('cleanPath', () => {
72 | it('should work', () => {
73 | const path = cleanPath('//a//b//d/')
74 | expect(path).toBe('/a/b/d/')
75 | })
76 | })
77 | })
78 |
--------------------------------------------------------------------------------
/docs/ru/advanced/lazy-loading.md:
--------------------------------------------------------------------------------
1 | # Ленивая загрузка путей
2 |
3 | При использовании модульного сборщика, результирующая JavaScript-сборка может оказаться довольно большой, что негативно сказывается на времени загрузки страницы. В некоторых случаях было бы эффективнее разделить компоненты каждого пути на отдельные минисборки, и загружать их только при переходе к соответствующему пути.
4 |
5 | Совместное использование [асинхронной загрузки компонентов](http://vuejs.org/guide/components.html#Async-Components) Vue и [разделения кода](https://webpack.js.org/guides/code-splitting-require/) WebPack делает реализацию ленивой загрузки компонентов в зависимости от путей тривиальной.
6 |
7 | Всё, что требуется — определить компоненты путей как асинхронные:
8 |
9 | ``` js
10 | const Foo = resolve => {
11 | // require.ensure — это специальный синтаксис Webpack'а для определения точки разделения кода.
12 | require.ensure(['./Foo.vue'], () => {
13 | resolve(require('./Foo.vue'))
14 | })
15 | }
16 | ```
17 |
18 | Можно также упростить запись, используя альтернативный синтаксис разделения кода AMD:
19 |
20 | ``` js
21 | const Foo = resolve => require(['./Foo.vue'], resolve)
22 | ```
23 |
24 | В конфигурации путей ничего менять не нужно, просто используйте `Foo` как обычно:
25 |
26 | ``` js
27 | const router = new VueRouter({
28 | routes: [
29 | { path: '/foo', component: Foo }
30 | ]
31 | })
32 | ```
33 |
34 | ### Объединение компонентов в единую минисборку
35 |
36 | Иногда может понадобиться объединить в единую минисборку все компоненты, расположенные по определённому пути. Для достижения этой цели можно использовать [именованные минисборки Webpack](https://webpack.js.org/guides/code-splitting-require/#chunkname), указывая имя как третий параметр при вызове `require.ensure`:
37 |
38 | ``` js
39 | const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo')
40 | const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo')
41 | const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
42 | ```
43 |
44 | Webpack сгруппирует все одноимённые асинхронные модули в единую минисборку — что среди прочего будет означать отсутствие необходимости явно указывать зависимости для `require.ensure` (поэтому мы и передаём первым параметром пустой массив).
45 |
--------------------------------------------------------------------------------