From 48fa4f2dbccaf01bed81947dc96a8f16bb12592d Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 14 Nov 2016 15:57:21 +0200 Subject: [PATCH 01/66] add entry for Russian docs --- docs/LANGS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/LANGS.md b/docs/LANGS.md index 0e59b8d30..fcac1b899 100644 --- a/docs/LANGS.md +++ b/docs/LANGS.md @@ -1,4 +1,5 @@ * [2.0 - English](en/) * [2.0 - Japanese](ja/) * [2.0 - 中文](zh-cn/) +* [2.0 - Русский](ru/) * [0.7 Docs](old/) From 2c3a5ea3e27ef11befc2dab9e07a07d4cf5cbfc7 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 14 Nov 2016 16:01:09 +0200 Subject: [PATCH 02/66] copy en docs for ru translation --- docs/ru/README.md | 30 ++++++ docs/ru/SUMMARY.md | 30 ++++++ docs/ru/advanced/data-fetching.md | 114 ++++++++++++++++++++++ docs/ru/advanced/lazy-loading.md | 45 +++++++++ docs/ru/advanced/meta.md | 51 ++++++++++ docs/ru/advanced/navigation-guards.md | 95 ++++++++++++++++++ docs/ru/advanced/scroll-behavior.md | 61 ++++++++++++ docs/ru/advanced/transitions.md | 58 +++++++++++ docs/ru/api/component-injections.md | 20 ++++ docs/ru/api/options.md | 69 +++++++++++++ docs/ru/api/route-object.md | 87 +++++++++++++++++ docs/ru/api/router-instance.md | 41 ++++++++ docs/ru/api/router-link.md | 118 +++++++++++++++++++++++ docs/ru/api/router-view.md | 27 ++++++ docs/ru/essentials/dynamic-matching.md | 62 ++++++++++++ docs/ru/essentials/getting-started.md | 69 +++++++++++++ docs/ru/essentials/history-mode.md | 60 ++++++++++++ docs/ru/essentials/named-routes.md | 32 ++++++ docs/ru/essentials/named-views.md | 30 ++++++ docs/ru/essentials/navigation.md | 67 +++++++++++++ docs/ru/essentials/nested-routes.md | 100 +++++++++++++++++++ docs/ru/essentials/redirect-and-alias.md | 58 +++++++++++ docs/ru/installation.md | 43 +++++++++ 23 files changed, 1367 insertions(+) create mode 100644 docs/ru/README.md create mode 100644 docs/ru/SUMMARY.md create mode 100644 docs/ru/advanced/data-fetching.md create mode 100644 docs/ru/advanced/lazy-loading.md create mode 100644 docs/ru/advanced/meta.md create mode 100644 docs/ru/advanced/navigation-guards.md create mode 100644 docs/ru/advanced/scroll-behavior.md create mode 100644 docs/ru/advanced/transitions.md create mode 100644 docs/ru/api/component-injections.md create mode 100644 docs/ru/api/options.md create mode 100644 docs/ru/api/route-object.md create mode 100644 docs/ru/api/router-instance.md create mode 100644 docs/ru/api/router-link.md create mode 100644 docs/ru/api/router-view.md create mode 100644 docs/ru/essentials/dynamic-matching.md create mode 100644 docs/ru/essentials/getting-started.md create mode 100644 docs/ru/essentials/history-mode.md create mode 100644 docs/ru/essentials/named-routes.md create mode 100644 docs/ru/essentials/named-views.md create mode 100644 docs/ru/essentials/navigation.md create mode 100644 docs/ru/essentials/nested-routes.md create mode 100644 docs/ru/essentials/redirect-and-alias.md create mode 100644 docs/ru/installation.md diff --git a/docs/ru/README.md b/docs/ru/README.md new file mode 100644 index 000000000..d88d82b23 --- /dev/null +++ b/docs/ru/README.md @@ -0,0 +1,30 @@ +# vue-router 2 + +> 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). + +**[Release Notes](https://github.com/vuejs/vue-router/releases)** + +- [Installation](installation.md) +- Essentials + - [Getting Started](essentials/getting-started.md) + - [Dynamic Route Matching](essentials/dynamic-matching.md) + - [Nested Routes](essentials/nested-routes.md) + - [Programmatic Navigation](essentials/navigation.md) + - [Named Routes](essentials/named-routes.md) + - [Named Views](essentials/named-views.md) + - [Redirect and Alias](essentials/redirect-and-alias.md) + - [HTML5 History Mode](essentials/history-mode.md) +- Advanced + - [Navigation Guards](advanced/navigation-guards.md) + - [Route Meta Fields](advanced/meta.md) + - [Transitions](advanced/transitions.md) + - [Data Fetching](advanced/data-fetching.md) + - [Scroll Behavior](advanced/scroll-behavior.md) + - [Lazy Loading](advanced/lazy-loading.md) +- API Reference + - [router-link](api/router-link.md) + - [router-view](api/router-view.md) + - [The Route Object](api/route-object.md) + - [Router Constructor Options](api/options.md) + - [Router Instance](api/router-instance.md) + - [Component Injections](api/component-injections.md) diff --git a/docs/ru/SUMMARY.md b/docs/ru/SUMMARY.md new file mode 100644 index 000000000..d88d82b23 --- /dev/null +++ b/docs/ru/SUMMARY.md @@ -0,0 +1,30 @@ +# vue-router 2 + +> 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). + +**[Release Notes](https://github.com/vuejs/vue-router/releases)** + +- [Installation](installation.md) +- Essentials + - [Getting Started](essentials/getting-started.md) + - [Dynamic Route Matching](essentials/dynamic-matching.md) + - [Nested Routes](essentials/nested-routes.md) + - [Programmatic Navigation](essentials/navigation.md) + - [Named Routes](essentials/named-routes.md) + - [Named Views](essentials/named-views.md) + - [Redirect and Alias](essentials/redirect-and-alias.md) + - [HTML5 History Mode](essentials/history-mode.md) +- Advanced + - [Navigation Guards](advanced/navigation-guards.md) + - [Route Meta Fields](advanced/meta.md) + - [Transitions](advanced/transitions.md) + - [Data Fetching](advanced/data-fetching.md) + - [Scroll Behavior](advanced/scroll-behavior.md) + - [Lazy Loading](advanced/lazy-loading.md) +- API Reference + - [router-link](api/router-link.md) + - [router-view](api/router-view.md) + - [The Route Object](api/route-object.md) + - [Router Constructor Options](api/options.md) + - [Router Instance](api/router-instance.md) + - [Component Injections](api/component-injections.md) diff --git a/docs/ru/advanced/data-fetching.md b/docs/ru/advanced/data-fetching.md new file mode 100644 index 000000000..aa520b1c5 --- /dev/null +++ b/docs/ru/advanced/data-fetching.md @@ -0,0 +1,114 @@ +# Data Fetching + +Sometimes you need to fetch data from the server when a route is activated. For example, before rendering a user profile, you need to fetch the user's data from the server. We can achieve this in two different ways: + +- **Fetching After Navigation**: perform the navigation first, and fetch data in the incoming component's lifecycle hook. Display a loading state while data is being fetched. + +- **Fetching Before Navigation**: Fetch data before navigation in the route enter guard, and perform the navigation after data has been fetched. + +Technically, both are valid choices - it ultimately depends on the user experience you are aiming for. + +## Fetching After Navigation + +When using this approach, we navigate and render the incoming component immediately, and fetch data in the component's `created` hook. It gives us the opportunity to display a loading state while the data is being fetched over the network, and we can also handle loading differently for each view. + +Let's assume we have a `Post` component that needs to fetch the data for a post based on `$route.params.id`: + +``` html + +``` + +``` js +export default { + data () { + return { + loading: false, + post: null, + error: null + } + }, + created () { + // fetch the data when the view is created and the data is + // already being observed + this.fetchData() + }, + watch: { + // call again the method if the route changes + '$route': 'fetchData' + }, + methods: { + fetchData () { + this.error = this.post = null + this.loading = true + // replace getPost with your data fetching util / API wrapper + getPost(this.$route.params.id, (err, post) => { + this.loading = false + if (err) { + this.error = err.toString() + } else { + this.post = post + } + }) + } + } +} +``` + +## Fetching Before Navigation + +With this approach we fetch the data before actually navigating to the new +route. We can perform the data fetching in the `beforeRouteEnter` guard in the incoming component, and only call `next` when the fetch is complete: + +``` js +export default { + data () { + return { + post: null, + error: null + } + }, + beforeRouteEnter (to, from, next) { + getPost(to.params.id, (err, post) => { + if (err) { + // display some global error message + next(false) + } else { + next(vm => { + vm.post = post + }) + } + }) + }, + // when route changes and this component is already rendered, + // the logic will be slightly different. + watch: { + $route () { + this.post = null + getPost(this.$route.params.id, (err, post) => { + if (err) { + this.error = err.toString() + } else { + this.post = post + } + }) + } + } +} +``` + +The user will stay on the current view while the resource is being fetched for the incoming view. It is therefore recommended to display a progress bar or some kind of indicator while the data is being fetched. If the data fetch fails, it's also necessary to display some kind of global warning message. diff --git a/docs/ru/advanced/lazy-loading.md b/docs/ru/advanced/lazy-loading.md new file mode 100644 index 000000000..31092194f --- /dev/null +++ b/docs/ru/advanced/lazy-loading.md @@ -0,0 +1,45 @@ +# Lazy Loading Routes + +When building apps with a bundler, the JavaScript bundle can become quite large and thus affecting 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. + +Combining Vue's [async component feature](http://vuejs.org/guide/components.html#Async-Components) and Webpack's [code splitting feature](https://webpack.github.io/docs/code-splitting.html), it's trivially easy to +lazy-load route components. + +All we need to do is defining our route components as async components: + +``` js +const Foo = resolve => { + // require.ensure is Webpack's special syntax for a code-split point. + require.ensure(['./Foo.vue'], () => { + resolve(require('./Foo.vue')) + }) +} +``` + +There's also an alternative code-split syntax using AMD style require, so this can be simplified to: + +``` js +const Foo = resolve => require(['./Foo.vue'], resolve) +``` + +Nothing needs to change in the route config, just use `Foo` as usual: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/foo', component: Foo } + ] +}) +``` + +### Grouping Components in the Same Chunk + +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.github.io/docs/code-splitting.html#named-chunks) by providing a chunk name to `require.ensure` as the 3rd argument: + +``` js +const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo') +const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo') +const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo') +``` + +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). diff --git a/docs/ru/advanced/meta.md b/docs/ru/advanced/meta.md new file mode 100644 index 000000000..79845b28d --- /dev/null +++ b/docs/ru/advanced/meta.md @@ -0,0 +1,51 @@ +# Route Meta Fields + +You can include a `meta` field when defining a route: + +``` js +const router = new VueRouter({ + routes: [ + { + path: '/foo', + component: Foo, + children: [ + { + path: 'bar', + component: Bar, + // a meta field + meta: { requiresAuth: true } + } + ] + } + ] +}) +``` + +So how do we access this `meta` field? + +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. + +For example, with the above route config, the URL `/foo/bar` will match both the parent route record and the child route record. + +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. + +An example use case is checking for a meta field in the global navigation guard: + +``` js +router.beforeEach((to, from, next) => { + if (to.matched.some(record => record.meta.requiresAuth)) { + // this route requires auth, check if logged in + // if not, redirect to login page. + if (!auth.loggedIn()) { + next({ + path: '/login', + query: { redirect: to.fullPath } + }) + } else { + next() + } + } else { + next() // make sure to always call next()! + } +}) +``` diff --git a/docs/ru/advanced/navigation-guards.md b/docs/ru/advanced/navigation-guards.md new file mode 100644 index 000000000..4a36ae1a3 --- /dev/null +++ b/docs/ru/advanced/navigation-guards.md @@ -0,0 +1,95 @@ +# Navigation Guards + +As the name suggests, the navigation guards provided by `vue-router` are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component. + +### Global Guards + +You can register global before guards using `router.beforeEach`: + +``` js +const router = new VueRouter({ ... }) + +router.beforeEach((to, from, next) => { + // ... +}) +``` + +Global before guards are called in creation order, whenever a navigation is triggered. Guards may be resolved asynchronously, and the navigation is considered **pending** before all hooks have been resolved. + +Every guard function receives three arguments: + +- **`to: Route`**: the target [Route Object](../api/route-object.md) being navigated to. + +- **`from: Route`**: the current route being navigated away from. + +- **`next: Function`**: this function must be called to **resolve** the hook. The action depends on the arguments provided to `next`: + + - **`next()`**: move on to the next hook in the pipeline. If no hooks are left, the navigation is **confirmed**. + + - **`next(false)`**: abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the `from` route. + + - **`next('/')` or `next({ path: '/' })`**: redirect to a different location. The current navigation will be aborted and a new one will be started. + +**Make sure to always call the `next` function, otherwise the hook will never be resolved.** + +You can also register global after hooks, however unlike guards, these hooks do not get a `next` function and cannot affect the navigation: + +``` js +router.afterEach((to, from) => { + // ... +}) +``` + +### Per-Route Guard + +You can define `beforeEnter` guards directly on a route's configuration object: + +``` js +const router = new VueRouter({ + routes: [ + { + path: '/foo', + component: Foo, + beforeEnter: (to, from, next) => { + // ... + } + } + ] +}) +``` + +These guards have the exact same signature as global before guards. + +### In-Component Guards + +Finally, you can directly define route navigation guards inside route components with `beforeRouteEnter` and `beforeRouteLeave`: + +``` js +const Foo = { + template: `...`, + beforeRouteEnter (to, from, next) { + // called before the route that renders this component is confirmed. + // does NOT have access to `this` component instance, + // because it has not been created yet when this guard is called! + }, + beforeRouteLeave (to, from, next) { + // called when the route that renders this component is about to + // be navigated away from. + // has access to `this` component instance. + } +} +``` + +The `beforeRouteEnter` guard does **NOT** have access to `this`, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet. + +However, you can access the instance by passing a callback to `next`. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument: + +``` js +beforeRouteEnter (to, from, next) { + next(vm => { + // access to component instance via `vm` + }) +} +``` + +You can directly access `this` inside `beforeRouteLeave`. The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by calling `next(false)`. diff --git a/docs/ru/advanced/scroll-behavior.md b/docs/ru/advanced/scroll-behavior.md new file mode 100644 index 000000000..46c511442 --- /dev/null +++ b/docs/ru/advanced/scroll-behavior.md @@ -0,0 +1,61 @@ +# Scroll Behavior + +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. + +**Note: this feature only works in HTML5 history mode.** + +When creating the router instance, you can provide the `scrollBehavior` function: + +``` js +const router = new VueRouter({ + routes: [...], + scrollBehavior (to, from, savedPosition) { + // return desired position + } +}) +``` + +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). + +The function can return a scroll position object. The object could be in the form of: + +- `{ x: number, y: number }` +- `{ selector: string }` + +If a falsy value or an empty object is returned, no scrolling will happen. + +For example: + +``` js +scrollBehavior (to, from, savedPosition) { + return { x: 0, y: 0 } +} +``` + +This will simply make the page scroll to top for all route navigations. + +Returning the `savedPosition` will result in a native-like behavior when navigating with back/forward buttons: + +``` js +scrollBehavior (to, from, savedPosition) { + if (savedPosition) { + return savedPosition + } else { + return { x: 0, y: 0 } + } +} +``` + +If you want to simulate the "scroll to anchor" behavior: + +``` js +scrollBehavior (to, from, savedPosition) { + if (to.hash) { + return { + selector: to.hash + } + } +} +``` + +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). diff --git a/docs/ru/advanced/transitions.md b/docs/ru/advanced/transitions.md new file mode 100644 index 000000000..d6595b23b --- /dev/null +++ b/docs/ru/advanced/transitions.md @@ -0,0 +1,58 @@ +# Transitions + +Since the `` is essentially a dynamic component, we can apply transition effects to it the same way using the `` component: + +``` html + + + +``` + +[Everything about ``](http://vuejs.org/guide/transitions.html) works the same here. + +### Per-Route Transition + +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: + +``` js +const Foo = { + template: ` + +
...
+
+ ` +} + +const Bar = { + template: ` + +
...
+
+ ` +} +``` + +### Route-Based Dynamic Transition + +It is also possible to determine the transition to use dynamically based on the relationship between the target route and current route: + +``` html + + + + +``` + +``` js +// then, in the parent component, +// watch the $route to determine the transition to use +watch: { + '$route' (to, from) { + const toDepth = to.path.split('/').length + const fromDepth = from.path.split('/').length + this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' + } +} +``` + +See full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). diff --git a/docs/ru/api/component-injections.md b/docs/ru/api/component-injections.md new file mode 100644 index 000000000..eceb5f657 --- /dev/null +++ b/docs/ru/api/component-injections.md @@ -0,0 +1,20 @@ +# Component Injections + +### Injected Properties + +These properties are injected into every child component by passing the router instance to the root instance as the `router` option. + +- #### $router + + The router instance. + +- #### $route + + The current active [Route](route-object.md). This property is read-only and its properties are immutable, but it can be watched. + +### Enabled Options + +- **beforeRouteEnter** +- **beforeRouteLeave** + + See [In Component Guards](../advanced/navigation-guards.md#incomponent-guards). diff --git a/docs/ru/api/options.md b/docs/ru/api/options.md new file mode 100644 index 000000000..b72f2ad50 --- /dev/null +++ b/docs/ru/api/options.md @@ -0,0 +1,69 @@ +# Router Construction Options + +### routes + +- type: `Array` + + Type declaration for `RouteConfig`: + + ``` js + declare type RouteConfig = { + path: string; + component?: Component; + name?: string; // for named routes + components?: { [name: string]: Component }; // for named views + redirect?: string | Location | Function; + alias?: string | Array; + children?: Array; // for nested routes + beforeEnter?: (to: Route, from: Route, next: Function) => void; + meta?: any; + } + ``` + +### mode + +- type: `string` + +- default: `"hash" (in browser) | "abstract" (in Node.js)` + +- available values: `"hash" | "history" | "abstract"` + + Configure the router mode. + + - `hash`: uses the URL hash for routing. Works in all Vue-supported browsers, including those that do not support HTML5 History API. + + - `history`: requires HTML5 History API and server config. See [HTML5 History Mode](../essentials/history-mode.md). + + - `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.** + +### base + +- type: `string` + +- default: `"/"` + + 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/"`. + +### linkActiveClass + +- type: `string` + +- default: `"router-link-active"` + + Globally configure `` default active class. Also see [router-link](router-link.md). + +### scrollBehavior + +- type: `Function` + + Signature: + + ``` + ( + to: Route, + from: Route, + savedPosition?: { x: number, y: number } + ) => { x: number, y: number } | { selector: string } | ?{} + ``` + + For more details see [Scroll Behavior](../advanced/scroll-behavior.md). diff --git a/docs/ru/api/route-object.md b/docs/ru/api/route-object.md new file mode 100644 index 000000000..e66dc4ec4 --- /dev/null +++ b/docs/ru/api/route-object.md @@ -0,0 +1,87 @@ +# The Route Object + +A **route object** represents the state of the current active route. It contains parsed information of the current URL and the **route records** matched by the URL. + +The route object is immutable. Every successful navigation will result in a fresh route object. + +The route object can be found in multiple places: + +- Inside components as `this.$route`, and obvious inside `$route` watcher callbacks; + +- As the return value of calling `router.match(location)`; + +- Inside navigation guards as the first two arguments: + + ``` js + router.beforeEach((to, from, next) => { + // to and from are both route objects + }) + ``` + +- Inside the `scrollBehavior` function as the first two arguments: + + ``` js + const router = new VueRouter({ + scrollBehavior (to, from, savedPosition) { + // to and from are both route objects + } + }) + ``` + +### Route Object Properties + +- **$route.path** + + - type: `string` + + A string that equals the path of the current route, always resolved as an absolute path. e.g. `"/foo/bar"`. + +- **$route.params** + + - type: `Object` + + An object that contains key/value pairs of dynamic segments and star segments. If there are no params the value will be an empty object. + +- **$route.query** + + - type: `Object` + + An object that contains key/value pairs of the query string. For example, for a path `/foo?user=1`, we get `$route.query.user == 1`. If there is no query the value will be an empty object. + +- **$route.hash** + + - type: `string` + + The hash of the current route (without `#`), if it has one. If no hash is present the value will be an empty string. + +- **$route.fullPath** + + - type: `string` + + The full resolved URL including query and hash. + +- **$route.matched** + + - type: `Array` + + An Array containing **route records** for all nested path segments of the current route. Route records are the copies of the objects in the `routes` configuration Array (and in `children` Arrays): + + ``` js + const router = new VueRouter({ + routes: [ + // the following object is a route record + { path: '/foo', component: Foo, + children: [ + // this is also a route record + { path: 'bar', component: Bar } + ] + } + ] + }) + ``` + + When the URL is `/foo/bar`, `$route.matched` will be an Array containing both objects (cloned), in parent to child order. + +- **$route.name** + + The name of the current route, if it has one. (See [Named Routes](../essentials/named-routes.md)) diff --git a/docs/ru/api/router-instance.md b/docs/ru/api/router-instance.md new file mode 100644 index 000000000..4bebc2a2f --- /dev/null +++ b/docs/ru/api/router-instance.md @@ -0,0 +1,41 @@ +# Router Instance + +### Properties + +#### router.app + +- type: `Vue instance` + + The root Vue instance the `router` was injected into. + +#### router.mode + +- type: `string` + + The [mode](options.md#mode) the router is using. + +#### router.currentRoute + +- type: `Route` + + The current route represented as a [Route Object](route-object.md). + +### Methods + +- **router.beforeEach(guard)** +- **router.afterEach(hook)** + + Add global navigation guards. See [Navigation Guards](../advanced/navigation-guards.md). + + +- **router.push(location)** +- **router.replace(location)** +- **router.go(n)** +- **router.back()** +- **router.forward()** + + Programmatically navigate to a new URL. See [Programmatic Navigation](../essentials/navigation.md). + +- **router.getMatchedComponents()** + + Returns an Array of the components (definition/constructor, not instances) matched by the current route. This is mostly used during server-side rendering to perform data prefetching. diff --git a/docs/ru/api/router-link.md b/docs/ru/api/router-link.md new file mode 100644 index 000000000..b493fb6a5 --- /dev/null +++ b/docs/ru/api/router-link.md @@ -0,0 +1,118 @@ +# `` + +`` is the component for enabling user navigation in a router-enabled app. The target location is specified with the `to` prop. It renders as an `` tag with correct `href` by default, but can be configured with the `tag` prop. In addition, the link automatically gets an active CSS class when the target route is active. + +`` is preferred over hard-coded `` for the following reasons: + +- It works the same way in both HTML5 history mode and hash mode, so if you ever decide to switch mode, or when the router falls back to hash mode in IE9, nothing needs to be changed. + +- In HTML5 history mode, `router-link` will intercept the click event so that the browser doesn't try to reload the page. + +- When you are using the `base` option in HTML5 history mode, you don't need to include it in `to` prop's URLs. + +### Props + +- **to** + + - type: `string | Location` + + - required + + Denotes the target route of the link. When clicked, the value of the `to` prop will be passed to `router.push()` internally, so the value can be either a string or a location descriptor object. + + ``` html + + Home + + Home + + + Home + + + Home + + + Home + + + User + + + Register + ``` + +- **replace** + + - type: `boolean` + + - default: `false` + + Setting `replace` prop will call `router.replace()` instead of `router.push()` when clicked, so the navigation will not leave a history record. + + ``` html + + ``` + +- **append** + + - type: `boolean` + + - default: `false` + + Setting `append` prop always appends the relative path to the current path. For example, assuming we are navigating from `/a` to a relative link `b`, without `append` we will end up at `/b`, but with `append` we will end up at `/a/b`. + + ``` html + + ``` + +- **tag** + + - type: `string` + + - default: `"a"` + + Sometimes we want `` to render as another tag, e.g `
  • `. Then we can use `tag` prop to specify which tag to render to, and it will still listen to click events for navigation. + + ``` html + foo + +
  • foo
  • + ``` + +- **active-class** + + - type: `string` + + - default: `"router-link-active"` + + Configure the active CSS class applied when the link is active. Note the default value can also be configured globally via the `linkActiveClass` router constructor option. + +- **exact** + + - type: `boolean` + + - default: `false` + + The default active class matching behavior is **inclusive match**. For example, `` will get this class applied as long as the current path starts with `/a`. + + One consequence of this is that `` will be active for every route! To force the link into "exact match mode", use the `exact` prop: + + ``` html + + + ``` + + Checkout more examples explaining active link class [live](http://jsfiddle.net/fnlCtrl/dokbyypq/). + +### Applying Active Class to Outer Element + +Sometimes we may want the active class to be applied to an outer element rather than the `` tag itself, in that case, you can render that outer element using `` and wrap the raw `` tag inside: + +``` html + + /foo + +``` + +In this case the `` will be the actual link (and will get the correct `href`), but the active class will be applied to the outer `
  • `. diff --git a/docs/ru/api/router-view.md b/docs/ru/api/router-view.md new file mode 100644 index 000000000..7e504f6ea --- /dev/null +++ b/docs/ru/api/router-view.md @@ -0,0 +1,27 @@ +# `` + +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. + +### Props + +- **name** + + - type: `string` + + - default: `"default"` + + 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. + +### Behavior + +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. + +Since it's just a component, it works with `` and ``. When using the both together, make sure to use `` inside: + +``` html + + + + + +``` diff --git a/docs/ru/essentials/dynamic-matching.md b/docs/ru/essentials/dynamic-matching.md new file mode 100644 index 000000000..f1afa1dd4 --- /dev/null +++ b/docs/ru/essentials/dynamic-matching.md @@ -0,0 +1,62 @@ +# Dynamic Route Matching + +Very often we will need to map routes with the given pattern to the same component. For example we may have a `User` component which should be rendered for all users but with different user IDs. In `vue-router` we can use a dynamic segment in the path to achieve that: + +``` js +const User = { + template: '
    User
    ' +} + +const router = new VueRouter({ + routes: [ + // dynamic segments start with a colon + { path: '/user/:id', component: User } + ] +}) +``` + +Now URLs like `/user/foo` and `/user/bar` will both map to the same route. + +A dynamic segment is denoted by a colon `:`. When a route is matched, the value of the dynamic segments will be exposed as `this.$route.params` in every component. Therefore, we can render the current user ID by updating `User`'s template to this: + +``` js +const User = { + template: '
    User {{ $route.params.id }}
    ' +} +``` + +You can checkout a live example [here](http://jsfiddle.net/yyx990803/4xfa2f19/). + +You can have multiple dynamic segments in the same route, and they will map to corresponding fields on `$route.params`. Examples: + +| pattern | matched path | $route.params | +|---------|------|--------| +| /user/:username | /user/evan | `{ username: 'evan' }` | +| /user/:username/post/:post_id | /user/evan/post/123 | `{ username: 'evan', post_id: 123 }` | + +In addition to `$route.params`, the `$route` object also exposes other useful information such as `$route.query` (if there is a query in the URL), `$route.hash`, etc. You can check out the full details in the [API Reference](../api/route-object.md). + +### Reacting to Params Changes + +One thing to note when using routes with params is that when the user navigates from `/user/foo` to `/user/bar`, **the same component instance will be reused**. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. **However, this also means that the lifecycle hooks of the component will not be called**. + +To react to params changes in the same component, you can simply watch the `$route` object: + +``` js +const User = { + template: '...', + watch: { + '$route' (to, from) { + // react to route changes... + } + } +} +``` + +### Advanced Matching Patterns + +`vue-router` uses [path-to-regexp](https://github.com/pillarjs/path-to-regexp) as its path matching engine, so it supports many advanced matching patterns such as optional dynamic segments, zero or more / one or more requirements, and even custom regex patterns. Check out its [documentation](https://github.com/pillarjs/path-to-regexp#parameters) for these advanced patterns, and [this example](https://github.com/vuejs/vue-router/blob/dev/examples/route-matching/app.js) of using them in `vue-router`. + +### Matching Priority + +Sometimes the same URL may be matched by multiple routes. In such a case the matching priority is determined by the order of route definition: the earlier a route is defined, the higher priority it gets. diff --git a/docs/ru/essentials/getting-started.md b/docs/ru/essentials/getting-started.md new file mode 100644 index 000000000..6ec89648d --- /dev/null +++ b/docs/ru/essentials/getting-started.md @@ -0,0 +1,69 @@ +# Getting Started + +> We will be using [ES2015](https://github.com/lukehoban/es6features) in the code samples in the guide. + +Creating a Single-page Application with Vue.js + vue-router is dead simple. With Vue.js, we are already composing our application with components. When adding vue-router to the mix, all we need to do is map our components to the routes and let vue-router know where to render them. Here's a basic example: + +> All examples will be using the standalone version of vue to make template parsing possible. See more details [here](http://vuejs.org/guide/installation.html#Standalone-vs-Runtime-only-Build) + +### HTML + +``` html + + + +
    +

    Hello App!

    +

    + + + + Go to Foo + Go to Bar +

    + + + +
    +``` + +### JavaScript + +``` js +// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter and then call Vue.use(VueRouter). + +// 1. Define route components. +// These can be imported from other files +const Foo = { template: '
    foo
    ' } +const Bar = { template: '
    bar
    ' } + +// 2. Define some routes +// Each route should map to a component. The "component" can +// either be an actual component constructor created via +// Vue.extend(), or just a component options object. +// We'll talk about nested routes later. +const routes = [ + { path: '/foo', component: Foo }, + { path: '/bar', component: Bar } +] + +// 3. Create the router instance and pass the `routes` option +// You can pass in additional options here, but let's +// keep it simple for now. +const router = new VueRouter({ + routes // short for routes: routes +}) + +// 4. Create and mount the root instance. +// Make sure to inject the router with the router option to make the +// whole app router-aware. +const app = new Vue({ + router +}).$mount('#app') + +// Now the app has started! +``` + +You can also checkout this example [live](http://jsfiddle.net/yyx990803/xgrjzsup/). + +Notice that a `` automatically gets the `.router-link-active` class when its target route is matched. You can learn more about it in its [API reference](../api/router-link.md). diff --git a/docs/ru/essentials/history-mode.md b/docs/ru/essentials/history-mode.md new file mode 100644 index 000000000..56c55ffdc --- /dev/null +++ b/docs/ru/essentials/history-mode.md @@ -0,0 +1,60 @@ +# HTML5 History Mode + +The default mode for `vue-router` is _hash mode_ - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. + +To get rid of the hash, we can use the router's **history mode**, which leverages the `history.pushState` API to achieve URL navigation without a page reload: + +``` js +const router = new VueRouter({ + mode: 'history', + routes: [...] +}) +``` + +When using history mode, the URL will look "normal," e.g. `http://oursite.com/user/id`. Beautiful! + +Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access `http://oursite.com/user/id` directly in their browser. Now that's ugly. + +Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same `index.html` page that your app lives in. Beautiful, again! + +## Example Server Configurations + +#### Apache + +```apache + + RewriteEngine On + RewriteBase / + RewriteRule ^index\.html$ - [L] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule . /index.html [L] + +``` + +#### nginx + +```nginx +location / { + try_files $uri $uri/ /index.html; +} +``` + +#### Node.js (Express) + +For Node.js/Express, consider using [connect-history-api-fallback middleware](https://github.com/bripkens/connect-history-api-fallback). + +## Caveat + +There is a caveat to this: Your server will no longer report 404 errors as all not-found paths now serve up your `index.html` file. To get around the issue, you should implement a catch-all route within your Vue app to show a 404 page: + +``` js +const router = new VueRouter({ + mode: 'history', + routes: [ + { path: '*', component: NotFoundComponent } + ] +}) +``` + +Alternatively, if you are using a Node.js server, you can implement the fallback by using the router on the server side to match the incoming URL and respond with 404 if no route is matched. diff --git a/docs/ru/essentials/named-routes.md b/docs/ru/essentials/named-routes.md new file mode 100644 index 000000000..2c8359736 --- /dev/null +++ b/docs/ru/essentials/named-routes.md @@ -0,0 +1,32 @@ +# Named Routes + +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: + +``` js +const router = new VueRouter({ + routes: [ + { + path: '/user/:userId', + name: 'user', + component: User + } + ] +}) +``` + +To link to a named route, you can pass an object to the `router-link` +component's `to` prop: + +``` html +User +``` + +This is the exact same object used programatically with `router.push()`: + +``` js +router.push({ name: 'user', params: { userId: 123 }}) +``` + +In both cases, the router will navigate to the path `/user/123`. + +Full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). diff --git a/docs/ru/essentials/named-views.md b/docs/ru/essentials/named-views.md new file mode 100644 index 000000000..8a78c5a9e --- /dev/null +++ b/docs/ru/essentials/named-views.md @@ -0,0 +1,30 @@ +# Named Views + +Sometimes you need to display multiples 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. + +``` html + + + +``` + +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 +an s) option: + +``` js +const router = new VueRouter({ + routes: [ + { + path: '/', + components: { + default: Foo, + a: Bar, + b: Baz + } + } + ] +}) +``` + +A working demo of this example can be found +[here](https://jsfiddle.net/posva/6du90epg/). diff --git a/docs/ru/essentials/navigation.md b/docs/ru/essentials/navigation.md new file mode 100644 index 000000000..f34f1945c --- /dev/null +++ b/docs/ru/essentials/navigation.md @@ -0,0 +1,67 @@ +# Programmatic Navigation + +Aside from using `` to create anchor tags for declarative navigation, we can do this programmatically using the router's instance methods. + +#### `router.push(location)` + +To navigate to a different URL, use `router.push`. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL. + +This is the method called internally when you click a ``, so clicking `` is the equivalent of calling `router.push(...)`. + +| Declarative | Programmatic | +|-------------|--------------| +| `` | `router.push(...)` | + +The argument can be a string path, or a location descriptor object. Examples: + +``` js +// literal string +router.push('home') + +// object +router.push({ path: 'home' }) + +// named route +router.push({ name: 'user', params: { userId: 123 }}) + +// with query, resulting in /register?plan=private +router.push({ path: 'register', query: { plan: 'private' }}) +``` + +#### `router.replace(location)` + +It acts like `router.push`, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry. + +| Declarative | Programmatic | +|-------------|--------------| +| `` | `router.replace(...)` | + + +#### `router.go(n)` + +This method takes a single integer as parameter that indicates by how many steps to go forwards or go backwards in the history stack, similar to `window.history.go(n)`. + +Examples + +``` js +// go forward by one record, the same as history.forward() +router.go(1) + +// go back by one record, the same as history.back() +router.go(-1) + +// go forward by 3 records +router.go(3) + +// fails silently if there aren't that many records. +router.go(-100) +router.go(100) +``` + +#### History Manipulation + +You may have noticed that `router.push`, `router.replace` and `router.go` are counterparts of [`window.history.pushState`, `window.history.replaceState` and `window.history.go`](https://developer.mozilla.org/en-US/docs/Web/API/History), and they do imitate the `window.history` APIs. + +Therefore, if you are already familiar with [Browser History APIs](https://developer.mozilla.org/en-US/docs/Web/API/History_API), manipulating history will be super easy with vue-router. + +It is worth mentioning that vue-router navigation methods (`push`, `replace`, `go`) work consistently in all router modes (`history`, `hash` and `abstract`). diff --git a/docs/ru/essentials/nested-routes.md b/docs/ru/essentials/nested-routes.md new file mode 100644 index 000000000..35241f0f4 --- /dev/null +++ b/docs/ru/essentials/nested-routes.md @@ -0,0 +1,100 @@ +# Nested Routes + +Real app UIs are usually composed of components that are nested multiple levels deep. It is also very common that the segments of a URL corresponds to a certain structure of nested components, for example: + +``` +/user/foo/profile /user/foo/posts ++------------------+ +-----------------+ +| User | | User | +| +--------------+ | | +-------------+ | +| | Profile | | +------------> | | Posts | | +| | | | | | | | +| +--------------+ | | +-------------+ | ++------------------+ +-----------------+ +``` + +With `vue-router`, it is very simple to express this relationship using nested route configurations. + +Given the app we created in the last chapter: + +``` html +
    + +
    +``` + +``` js +const User = { + template: '
    User {{ $route.params.id }}
    ' +} + +const router = new VueRouter({ + routes: [ + { path: '/user/:id', component: User } + ] +}) +``` + +The `` here is a top-level outlet. It renders the component matched by a top level route. Similarly, a rendered component can also contain its own, nested ``. For example, if we add one inside the `User` component's template: + +``` js +const User = { + template: ` +
    +

    User {{ $route.params.id }}

    + +
    + ` +} +``` + +To render components into this nested outlet, we need to use the `children` +option in `VueRouter` constructor config: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/user/:id', component: User, + children: [ + { + // UserProfile will be rendered inside User's + // when /user/:id/profile is matched + path: 'profile', + component: UserProfile + }, + { + // UserPosts will be rendered inside User's + // when /user/:id/posts is matched + path: 'posts', + component: UserPosts + } + ] + } + ] +}) +``` + +**Note that nested paths that start with `/` will be treated as a root path. This allows you to leverage the component nesting without having to use a nested URL.** + +As you can see the `children` option is just another Array of route configuration objects like `routes` itself. Therefore, you can keep nesting views as much as you need. + +At this point, with the above configuration, when you visit `/user/foo`, nothing will be rendered inside `User`'s outlet, because no sub route is matched. Maybe you do want to render something there. In such case you can provide an empty subroute path: + +``` js +const router = new VueRouter({ + routes: [ + { + path: '/user/:id', component: User, + children: [ + // UserHome will be rendered inside User's + // when /user/:id is matched + { path: '', component: UserHome }, + + // ...other sub routes + ] + } + ] +}) +``` + +A working demo of this example can be found [here](http://jsfiddle.net/yyx990803/L7hscd8h/). diff --git a/docs/ru/essentials/redirect-and-alias.md b/docs/ru/essentials/redirect-and-alias.md new file mode 100644 index 000000000..b23aa95d7 --- /dev/null +++ b/docs/ru/essentials/redirect-and-alias.md @@ -0,0 +1,58 @@ +# Redirect and Alias + +### Redirect + +Redirecting is also done in the `routes` configuration. To redirect from `/a` to `/b`: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/a', redirect: '/b' } + ] +}) +``` + +The redirect can also be targeting a named route: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/a', redirect: { name: 'foo' }} + ] +}) +``` + +Or even use a function for dynamic redirecting: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/a', redirect: to => { + // the function receives the target route as the argument + // return redirect path/location here. + }} + ] +}) +``` + +For other advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js). + +### Alias + +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? + +**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`.** + +The above can be expressed in the route configuration as: + +``` js +const router = new VueRouter({ + routes: [ + { path: '/a', component: A, alias: '/b' } + ] +}) +``` + +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. + +For advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js). diff --git a/docs/ru/installation.md b/docs/ru/installation.md new file mode 100644 index 000000000..b5f4a99a2 --- /dev/null +++ b/docs/ru/installation.md @@ -0,0 +1,43 @@ +# Installation + +### Direct Download / CDN + +[https://unpkg.com/vue-router](https://unpkg.com/vue-router) + +[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`. + +Include `vue-router` after Vue and it will install itself automatically: + +``` html + + +``` + +### NPM + +``` bash +npm install vue-router +``` + +When used with a module system, you must explicitly install the router via `Vue.use()`: + +``` js +import Vue from 'vue' +import VueRouter from 'vue-router' + +Vue.use(VueRouter) +``` + +You don't need to do this when using global script tags. + +### Dev Build + +You will have to clone directly from GitHub and build `vue-router` yourself if +you want to use the latest dev build. + +``` bash +git clone https://github.com/vuejs/vue-router.git node_modules/vue-router +cd node_modules/vue-router +npm install +npm run build +``` From 18fa268745ff3ca38c65fa4bf21a34b1b3812d17 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Sun, 27 Nov 2016 22:19:54 +0200 Subject: [PATCH 03/66] translation for ru/installation.md --- docs/ru/installation.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/ru/installation.md b/docs/ru/installation.md index b5f4a99a2..2a4fbdd31 100644 --- a/docs/ru/installation.md +++ b/docs/ru/installation.md @@ -1,12 +1,12 @@ -# Installation +# Установка -### Direct Download / CDN +### Локальный файл / CDN [https://unpkg.com/vue-router](https://unpkg.com/vue-router) -[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`. +[Unpkg.com](https://unpkg.com) предоставляет CDN-ссылки для NPM-пакетов. Ссылка выше всегда указывает на самую свежую версию vue-router, доступную в NPM. Можно указать и конкретную версию или тег, используя ссылки вида `https://unpkg.com/vue-router@2.0.0`. -Include `vue-router` after Vue and it will install itself automatically: +Подключите `vue-router` после Vue, и установка произойдёт автоматически: ``` html @@ -19,7 +19,7 @@ Include `vue-router` after Vue and it will install itself automatically: npm install vue-router ``` -When used with a module system, you must explicitly install the router via `Vue.use()`: +При использовании модульной системы сборки, необходимо явно обозначить использование роутера при помощи `Vue.use()`: ``` js import Vue from 'vue' @@ -28,12 +28,11 @@ import VueRouter from 'vue-router' Vue.use(VueRouter) ``` -You don't need to do this when using global script tags. +При использовании глобальных скриптов в этом нет необходимости. -### Dev Build +### Dev-Сборка -You will have to clone directly from GitHub and build `vue-router` yourself if -you want to use the latest dev build. +Если вы хотите использовать версию `vue-router` в разработке, склонируйте репозиторий с GitHub и выполните сборку вручную: ``` bash git clone https://github.com/vuejs/vue-router.git node_modules/vue-router From 72a19cb10073b0b2acbf8b0e78e41cfb6a146eb0 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Sun, 27 Nov 2016 22:33:01 +0200 Subject: [PATCH 04/66] ru/README.md translation --- docs/ru/README.md | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/docs/ru/README.md b/docs/ru/README.md index d88d82b23..0355ca169 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,30 +1,30 @@ # vue-router 2 -> 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). +> Обратите внимание: vue-router@2.x работает только с Vue 2.x. Документация для версии 0.7.x находится [здесь (en)](https://github.com/vuejs/vue-router/tree/1.0/docs/en). **[Release Notes](https://github.com/vuejs/vue-router/releases)** -- [Installation](installation.md) -- Essentials - - [Getting Started](essentials/getting-started.md) - - [Dynamic Route Matching](essentials/dynamic-matching.md) - - [Nested Routes](essentials/nested-routes.md) - - [Programmatic Navigation](essentials/navigation.md) - - [Named Routes](essentials/named-routes.md) - - [Named Views](essentials/named-views.md) - - [Redirect and Alias](essentials/redirect-and-alias.md) - - [HTML5 History Mode](essentials/history-mode.md) -- Advanced - - [Navigation Guards](advanced/navigation-guards.md) - - [Route Meta Fields](advanced/meta.md) - - [Transitions](advanced/transitions.md) - - [Data Fetching](advanced/data-fetching.md) - - [Scroll Behavior](advanced/scroll-behavior.md) - - [Lazy Loading](advanced/lazy-loading.md) -- API Reference +- [Установка](installation.md) +- Основы + - [Начало работы](essentials/getting-started.md) + - [Динамические пути](essentials/dynamic-matching.md) + - [Вложенные пути](essentials/nested-routes.md) + - [Императивная навигация](essentials/navigation.md) + - [Именованные пути](essentials/named-routes.md) + - [Именованные представления](essentials/named-views.md) + - [Редиректы и псевдонимы](essentials/redirect-and-alias.md) + - [Режим HTML5 History](essentials/history-mode.md) +- Продвинутые возможности + - [Сторожевые хуки](advanced/navigation-guards.md) + - [Метаданные путей](advanced/meta.md) + - [Переходы](advanced/transitions.md) + - [Запросы данных](advanced/data-fetching.md) + - [Скроллинг](advanced/scroll-behavior.md) + - [Ленивая загрузка](advanced/lazy-loading.md) +- Справочник API - [router-link](api/router-link.md) - [router-view](api/router-view.md) - - [The Route Object](api/route-object.md) - - [Router Constructor Options](api/options.md) - - [Router Instance](api/router-instance.md) - - [Component Injections](api/component-injections.md) + - [Объект Route](api/route-object.md) + - [Опции конструктора Router'а](api/options.md) + - [Инстанс Router'а](api/router-instance.md) + - [Интеграция с компонентами Vue](api/component-injections.md) From fe6509dcad9bedc6cfb0f32c277af92e4bd13d1f Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Sun, 27 Nov 2016 22:35:34 +0200 Subject: [PATCH 05/66] ru/SUMMARY.md translation (same as README.md) --- docs/ru/SUMMARY.md | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/docs/ru/SUMMARY.md b/docs/ru/SUMMARY.md index d88d82b23..0355ca169 100644 --- a/docs/ru/SUMMARY.md +++ b/docs/ru/SUMMARY.md @@ -1,30 +1,30 @@ # vue-router 2 -> 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). +> Обратите внимание: vue-router@2.x работает только с Vue 2.x. Документация для версии 0.7.x находится [здесь (en)](https://github.com/vuejs/vue-router/tree/1.0/docs/en). **[Release Notes](https://github.com/vuejs/vue-router/releases)** -- [Installation](installation.md) -- Essentials - - [Getting Started](essentials/getting-started.md) - - [Dynamic Route Matching](essentials/dynamic-matching.md) - - [Nested Routes](essentials/nested-routes.md) - - [Programmatic Navigation](essentials/navigation.md) - - [Named Routes](essentials/named-routes.md) - - [Named Views](essentials/named-views.md) - - [Redirect and Alias](essentials/redirect-and-alias.md) - - [HTML5 History Mode](essentials/history-mode.md) -- Advanced - - [Navigation Guards](advanced/navigation-guards.md) - - [Route Meta Fields](advanced/meta.md) - - [Transitions](advanced/transitions.md) - - [Data Fetching](advanced/data-fetching.md) - - [Scroll Behavior](advanced/scroll-behavior.md) - - [Lazy Loading](advanced/lazy-loading.md) -- API Reference +- [Установка](installation.md) +- Основы + - [Начало работы](essentials/getting-started.md) + - [Динамические пути](essentials/dynamic-matching.md) + - [Вложенные пути](essentials/nested-routes.md) + - [Императивная навигация](essentials/navigation.md) + - [Именованные пути](essentials/named-routes.md) + - [Именованные представления](essentials/named-views.md) + - [Редиректы и псевдонимы](essentials/redirect-and-alias.md) + - [Режим HTML5 History](essentials/history-mode.md) +- Продвинутые возможности + - [Сторожевые хуки](advanced/navigation-guards.md) + - [Метаданные путей](advanced/meta.md) + - [Переходы](advanced/transitions.md) + - [Запросы данных](advanced/data-fetching.md) + - [Скроллинг](advanced/scroll-behavior.md) + - [Ленивая загрузка](advanced/lazy-loading.md) +- Справочник API - [router-link](api/router-link.md) - [router-view](api/router-view.md) - - [The Route Object](api/route-object.md) - - [Router Constructor Options](api/options.md) - - [Router Instance](api/router-instance.md) - - [Component Injections](api/component-injections.md) + - [Объект Route](api/route-object.md) + - [Опции конструктора Router'а](api/options.md) + - [Инстанс Router'а](api/router-instance.md) + - [Интеграция с компонентами Vue](api/component-injections.md) From 1e83812140351bb5270d05b5e46bead9e62bd755 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Sun, 27 Nov 2016 23:07:53 +0200 Subject: [PATCH 06/66] ru/essentials/getting-started.md ru translation --- docs/ru/essentials/getting-started.md | 52 +++++++++++++-------------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/docs/ru/essentials/getting-started.md b/docs/ru/essentials/getting-started.md index 6ec89648d..ae86d9db9 100644 --- a/docs/ru/essentials/getting-started.md +++ b/docs/ru/essentials/getting-started.md @@ -1,10 +1,10 @@ -# Getting Started +# Начало работы -> We will be using [ES2015](https://github.com/lukehoban/es6features) in the code samples in the guide. +> В примерах этого руководства мы будем использовать синтаксис [ES2015](https://github.com/lukehoban/es6features). -Creating a Single-page Application with Vue.js + vue-router is dead simple. With Vue.js, we are already composing our application with components. When adding vue-router to the mix, all we need to do is map our components to the routes and let vue-router know where to render them. Here's a basic example: +Создать одностраничное приложение используя Vue.js и vue-router — проще простого. Используя Vue.js, мы уже собираем своё приложение из компонентов. Добавляя vue-router, мы просто сопоставляем компонентам пути, и указываем где именно их отображать. Вот простой пример: -> All examples will be using the standalone version of vue to make template parsing possible. See more details [here](http://vuejs.org/guide/installation.html#Standalone-vs-Runtime-only-Build) +> Во всех примерах мы используем standalone-версию Vue, что позволяет использовать парсинг шаблонов. Более подробно о разнице версий можно почитать [здесь](http://vuejs.org/guide/installation.html#Standalone-vs-Runtime-only-Build). ### HTML @@ -15,14 +15,13 @@ Creating a Single-page Application with Vue.js + vue-router is dead simple. With

    Hello App!

    - - - + + + Go to Foo Go to Bar

    - - +
    ``` @@ -30,40 +29,39 @@ Creating a Single-page Application with Vue.js + vue-router is dead simple. With ### JavaScript ``` js -// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter and then call Vue.use(VueRouter). +// 0. Если вы используете модульную системы (напр. через vue-cli), импортируйте Vue и VueRouter и вызовите Vue.use(VueRouter). -// 1. Define route components. -// These can be imported from other files +// 1. Определите используемые компоненты. +// Их можно импортировать из внешних файлов const Foo = { template: '
    foo
    ' } const Bar = { template: '
    bar
    ' } -// 2. Define some routes -// Each route should map to a component. The "component" can -// either be an actual component constructor created via -// Vue.extend(), or just a component options object. -// We'll talk about nested routes later. +// 2. Определите пути +// Каждому пути должен соответствовать компонент. "Компонентом" может +// быть как созданный через Vue.extend() полноценный конструктор, +// так и просто объект опций компонента. +// Вложенные пути будут рассмотрены позднее. const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] -// 3. Create the router instance and pass the `routes` option -// You can pass in additional options here, but let's -// keep it simple for now. +// 3. Создайте инстанс роутера и передайте ему опцию `routes` +// Можно передать и другие опции, но пока не будем усложнять const router = new VueRouter({ - routes // short for routes: routes + routes // сокращение от routes: routes }) -// 4. Create and mount the root instance. -// Make sure to inject the router with the router option to make the -// whole app router-aware. +// 4. Создайте и примонтируйте корневой инстанс приложения +// Удостоверьтесь, что передали инстанс роутера в одноимённой опции, +// что даст приложению знать о его присутствии const app = new Vue({ router }).$mount('#app') -// Now the app has started! +// Всё, приложение работает ;) ``` -You can also checkout this example [live](http://jsfiddle.net/yyx990803/xgrjzsup/). +Вживую этот пример доступен [здесь](http://jsfiddle.net/yyx990803/xgrjzsup/). -Notice that a `` automatically gets the `.router-link-active` class when its target route is matched. You can learn more about it in its [API reference](../api/router-link.md). +Обратите внимание, что `` автоматически получает класс `.router-link-active` при совпадении пути. Более подробно об этом можно почитать в [справочнике API](../api/router-link.md). \ No newline at end of file From b59c83767fc27734adf06885e4689e054025a30e Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Sun, 27 Nov 2016 23:48:17 +0200 Subject: [PATCH 07/66] ru/essentials/dynamic-matching.md ru translation --- docs/ru/essentials/dynamic-matching.md | 32 +++++++++++++------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/ru/essentials/dynamic-matching.md b/docs/ru/essentials/dynamic-matching.md index f1afa1dd4..34a7ce549 100644 --- a/docs/ru/essentials/dynamic-matching.md +++ b/docs/ru/essentials/dynamic-matching.md @@ -1,6 +1,6 @@ -# Dynamic Route Matching +# Динамические пути -Very often we will need to map routes with the given pattern to the same component. For example we may have a `User` component which should be rendered for all users but with different user IDs. In `vue-router` we can use a dynamic segment in the path to achieve that: +Очень часто требуется поставить компонент в соответствие со множеством путей по некоторому шаблону. Например, мы можем захотеть отображать один и тот же компонент `User` для всего множества пользователей в соответствии с их ID. Во `vue-router` для этой цели мы можем указать динамический сегмент пути: ``` js const User = { @@ -9,38 +9,38 @@ const User = { const router = new VueRouter({ routes: [ - // dynamic segments start with a colon + // динамические сегменты начинаются с двоеточия { path: '/user/:id', component: User } ] }) ``` -Now URLs like `/user/foo` and `/user/bar` will both map to the same route. +Теперь все URL вида `/user/foo` или `/user/bar` соответствуют одному и тому же пути и компоненту. -A dynamic segment is denoted by a colon `:`. When a route is matched, the value of the dynamic segments will be exposed as `this.$route.params` in every component. Therefore, we can render the current user ID by updating `User`'s template to this: +Динамический сегмент обозначается двоеточием `:`. При совпадении пути, значение динамического сегмента становится доступно как `this.$route.params` для каждого компонента. Поэтому, мы можем отобразить ID текущего пользователя, используя такой шаблон: ``` js const User = { - template: '
    User {{ $route.params.id }}
    ' + template: '
    Пользователь {{ $route.params.id }}
    ' } ``` -You can checkout a live example [here](http://jsfiddle.net/yyx990803/4xfa2f19/). +Посмотреть на пример вживую можно [здесь](http://jsfiddle.net/yyx990803/4xfa2f19/). -You can have multiple dynamic segments in the same route, and they will map to corresponding fields on `$route.params`. Examples: +В рамках одного пути можно указать несколько динамических сегментов. Для каждого появится соответствующая запись в `$route.params`. Например: | pattern | matched path | $route.params | |---------|------|--------| | /user/:username | /user/evan | `{ username: 'evan' }` | | /user/:username/post/:post_id | /user/evan/post/123 | `{ username: 'evan', post_id: 123 }` | -In addition to `$route.params`, the `$route` object also exposes other useful information such as `$route.query` (if there is a query in the URL), `$route.hash`, etc. You can check out the full details in the [API Reference](../api/route-object.md). +Помимо `$route.params`, объект `$route` также позволяет получить доступ к другой полезной информации, например `$route.query` (если URL содержит строку запроса), `$route.hash`, и т.д. [Справочник API](../api/route-object.md) содержит подробное описание. -### Reacting to Params Changes +### Реакция на изменение параметров -One thing to note when using routes with params is that when the user navigates from `/user/foo` to `/user/bar`, **the same component instance will be reused**. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. **However, this also means that the lifecycle hooks of the component will not be called**. +Важно отметить, что при переходе от `/user/foo` к `/user/bar` **будет повторно использован тот же самый инстанс компонента**. Поскольку оба пути указывают на один и тот же компонент, этот подход эффективнее, чем уничтожение и повторное создание инстанса. **Вместе с тем, это означает, что хуки жизненного цикла компонента при этом вызваны не будут**. -To react to params changes in the same component, you can simply watch the `$route` object: +Чтобы отреагировать на изменения параметров в рамках компонента, можно напрямую установить наблюдение за объектом `$route`: ``` js const User = { @@ -53,10 +53,10 @@ const User = { } ``` -### Advanced Matching Patterns +### Продвинутые возможности -`vue-router` uses [path-to-regexp](https://github.com/pillarjs/path-to-regexp) as its path matching engine, so it supports many advanced matching patterns such as optional dynamic segments, zero or more / one or more requirements, and even custom regex patterns. Check out its [documentation](https://github.com/pillarjs/path-to-regexp#parameters) for these advanced patterns, and [this example](https://github.com/vuejs/vue-router/blob/dev/examples/route-matching/app.js) of using them in `vue-router`. +`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/dev/examples/route-matching/app.js) — о том, как использовать их с `vue-router`. -### Matching Priority +### Приоритеты путей -Sometimes the same URL may be matched by multiple routes. In such a case the matching priority is determined by the order of route definition: the earlier a route is defined, the higher priority it gets. +Иногда один и тот же URL может совпасть с несколькими путями. В таких случаях приоритет определяется порядком определения путей: чем раньше определён путь, тем выше у него приоритет. From 68492ebb913d17463c5438cafac9525cb35b2654 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 00:13:39 +0200 Subject: [PATCH 08/66] ru/essentials/nested-routes.md ru translation --- docs/ru/essentials/nested-routes.md | 40 ++++++++++++++--------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/ru/essentials/nested-routes.md b/docs/ru/essentials/nested-routes.md index 35241f0f4..178c5301a 100644 --- a/docs/ru/essentials/nested-routes.md +++ b/docs/ru/essentials/nested-routes.md @@ -1,6 +1,6 @@ -# Nested Routes +# Вложенные пути -Real app UIs are usually composed of components that are nested multiple levels deep. It is also very common that the segments of a URL corresponds to a certain structure of nested components, for example: +Пользовательский интерфейс реальных приложений обычно составлен многоуровневой иерархией компонентов. Столь же обычно и соответствие сегментов URL некоторой структуре вложенности компонентов, например: ``` /user/foo/profile /user/foo/posts @@ -13,9 +13,9 @@ Real app UIs are usually composed of components that are nested multiple levels +------------------+ +-----------------+ ``` -With `vue-router`, it is very simple to express this relationship using nested route configurations. +Используя `vue-router`, мы можем с лёгкостью выразить эти взаимоотношения при помощи вложенных путей. -Given the app we created in the last chapter: +Рассмотрим созданное в предыдущем разделе приложение: ``` html
    @@ -25,7 +25,7 @@ Given the app we created in the last chapter: ``` js const User = { - template: '
    User {{ $route.params.id }}
    ' + template: '
    Пользователь {{ $route.params.id }}
    ' } const router = new VueRouter({ @@ -35,21 +35,21 @@ const router = new VueRouter({ }) ``` -The `` here is a top-level outlet. It renders the component matched by a top level route. Similarly, a rendered component can also contain its own, nested ``. For example, if we add one inside the `User` component's template: +Здесь `` — это точка, в которой будет отображён компонент, соответствующий пути верхнего уровня. Аналогично, отображённый там компонент может и сам содержать вложенный ``. Изменим немного шаблон компонента `User`: ``` js const User = { template: `
    -

    User {{ $route.params.id }}

    +

    Пользователь {{ $route.params.id }}

    ` } ``` -To render components into this nested outlet, we need to use the `children` -option in `VueRouter` constructor config: +Для отображения компонентов в этой вложенной точке, нам понадобится опция `children` +в конфигурации конструктора `VueRouter`: ``` js const router = new VueRouter({ @@ -57,14 +57,14 @@ const router = new VueRouter({ { path: '/user/:id', component: User, children: [ { - // UserProfile will be rendered inside User's - // when /user/:id/profile is matched + // при совпадении пути с шаблоном /user/:id/profile + // в компонента User будет отображён UserProfile path: 'profile', component: UserProfile }, { - // UserPosts will be rendered inside User's - // when /user/:id/posts is matched + // при совпадении с шаблоном /user/:id/posts + // в компонента User будет отображён UserPosts path: 'posts', component: UserPosts } @@ -74,11 +74,11 @@ const router = new VueRouter({ }) ``` -**Note that nested paths that start with `/` will be treated as a root path. This allows you to leverage the component nesting without having to use a nested URL.** +**Обратите внимание, что вложенные пути, начинающиеся с `/`, будут считаться корневыми. Это позволяет задействовать вложенную структуру компонентов независимо от структуры URL.** -As you can see the `children` option is just another Array of route configuration objects like `routes` itself. Therefore, you can keep nesting views as much as you need. +Как вы могли заметить, опция `children` — это просто массив объектов конфигурации путей, такой же как и сам `routes`. Так что вложенность по глубине не ограничена. -At this point, with the above configuration, when you visit `/user/foo`, nothing will be rendered inside `User`'s outlet, because no sub route is matched. Maybe you do want to render something there. In such case you can provide an empty subroute path: +С текущим кодом, если перейти по пути `/user/foo`, внутри компонента `User` ничего отображено не будет, так как не произойдёт совпадения по второй части пути. Может быть, что-то в таких случаях отобразить всё же захочется — тогда стоит указать пустой путь: ``` js const router = new VueRouter({ @@ -86,15 +86,15 @@ const router = new VueRouter({ { path: '/user/:id', component: User, children: [ - // UserHome will be rendered inside User's - // when /user/:id is matched + // при совпадении пути с шаблоном /user/:id + // в компонента User будет отображён UserHome { path: '', component: UserHome }, - // ...other sub routes + // ...остальные вложенные пути ] } ] }) ``` -A working demo of this example can be found [here](http://jsfiddle.net/yyx990803/L7hscd8h/). +Действующее демо этого примера можно найти [здесь](http://jsfiddle.net/yyx990803/L7hscd8h/). From 8c56d4ae35ef5c54b4323641131cd41e5af58a8a Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 10:40:13 +0200 Subject: [PATCH 09/66] ru/essentials/navigation.md ru translation --- docs/ru/essentials/navigation.md | 44 ++++++++++++++++---------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/ru/essentials/navigation.md b/docs/ru/essentials/navigation.md index f34f1945c..0582091c8 100644 --- a/docs/ru/essentials/navigation.md +++ b/docs/ru/essentials/navigation.md @@ -1,67 +1,67 @@ -# Programmatic Navigation +# Императивная навигация -Aside from using `` to create anchor tags for declarative navigation, we can do this programmatically using the router's instance methods. +Помимо декларативного использования `` для создания ссылок, мы можем использовать роутер и императивно, вызывая методы его инстанса. #### `router.push(location)` -To navigate to a different URL, use `router.push`. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL. +Для перехода к новому URL, используйте `router.push`. Этот метод добавляет новую запись в стек истории навигации, так что клик по кнопке "назад" сработает привычным образом. -This is the method called internally when you click a ``, so clicking `` is the equivalent of calling `router.push(...)`. +При клике на `` этот метод вызывается автоматически. Клик по `` эквивалентен императивному вызову `router.push(...)`. -| Declarative | Programmatic | +| Декларативная запись | Императивная запись | |-------------|--------------| | `` | `router.push(...)` | -The argument can be a string path, or a location descriptor object. Examples: +В качестве аргумента можно передать строку или объект, описывающий путь. Например: ``` js -// literal string +// строка router.push('home') -// object +// объект router.push({ path: 'home' }) -// named route +// именованый путь router.push({ name: 'user', params: { userId: 123 }}) -// with query, resulting in /register?plan=private +// со строкой запроса, получится /register?plan=private router.push({ path: 'register', query: { plan: 'private' }}) ``` #### `router.replace(location)` -It acts like `router.push`, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry. +Действует подобно `router.push`, с той лишь разницей, что вместо добавления новой записи к стеку истории переходов, заменяет текущую запись в нём. -| Declarative | Programmatic | +| Декларативная запись | Императивная запись | |-------------|--------------| | `` | `router.replace(...)` | #### `router.go(n)` -This method takes a single integer as parameter that indicates by how many steps to go forwards or go backwards in the history stack, similar to `window.history.go(n)`. +Единственным параметром этого метода является целое число, указывающее на сколько шагов необходимо перейти по стеку истории навигации (вперёд или назад, аналогично `window.history.go(n)`). -Examples +Примеры ``` js -// go forward by one record, the same as history.forward() +// перейти на одну запись вперёд, эквивалентно history.forward() router.go(1) -// go back by one record, the same as history.back() +// перейти на одну запись назад, эквивалентно history.back() router.go(-1) -// go forward by 3 records +// перейти на 3 записи вперёд router.go(3) -// fails silently if there aren't that many records. +// если записей в истории недостаточно много, просто ничего не произойдёт router.go(-100) router.go(100) ``` -#### History Manipulation +#### Манипулирование историей переходов -You may have noticed that `router.push`, `router.replace` and `router.go` are counterparts of [`window.history.pushState`, `window.history.replaceState` and `window.history.go`](https://developer.mozilla.org/en-US/docs/Web/API/History), and they do imitate the `window.history` APIs. +Вы могли заметить6 что `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), имитируя таким образом API `window.history`. -Therefore, if you are already familiar with [Browser History APIs](https://developer.mozilla.org/en-US/docs/Web/API/History_API), manipulating history will be super easy with vue-router. +По этой причине, если вы уже знакомы с [API истории переходов браузера](https://developer.mozilla.org/en-US/docs/Web/API/History_API), и со vue-router неожиданностей не возникнет. -It is worth mentioning that vue-router navigation methods (`push`, `replace`, `go`) work consistently in all router modes (`history`, `hash` and `abstract`). +Стоит отметить, что методы навигации vue-router'а (`push`, `replace`, `go`) работают консистентно во всех режимах роутера (`history`, `hash` и `abstract`). \ No newline at end of file From c10f3400997749e5a8e84febe15ae14c17725bda Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 10:40:20 +0200 Subject: [PATCH 10/66] ru/essentials/named-routes.md ru translation --- docs/ru/essentials/named-routes.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/ru/essentials/named-routes.md b/docs/ru/essentials/named-routes.md index 2c8359736..da34d70b6 100644 --- a/docs/ru/essentials/named-routes.md +++ b/docs/ru/essentials/named-routes.md @@ -1,6 +1,6 @@ -# Named Routes +# Именованые пути -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: +Зачастую удобно ссылаться на путь по его имени при создании ссылок и вызове навигационных методов. Можно присвоить имя пути при его определении в `routes` при создании инстанса Router'а: ``` js const router = new VueRouter({ @@ -14,19 +14,18 @@ const router = new VueRouter({ }) ``` -To link to a named route, you can pass an object to the `router-link` -component's `to` prop: +Чтобы сослаться на именованный маршрут, используйте объектную запись: ``` html -User +Пользователь ``` -This is the exact same object used programatically with `router.push()`: +Тот же самый объект можно использовать и для императивного вызова `router.push()`: ``` js router.push({ name: 'user', params: { userId: 123 }}) ``` -In both cases, the router will navigate to the path `/user/123`. +В обоих случаях результатом будет навигационный переход на `/user/123`. -Full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). +Полный пример находится [здесь](https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js). From 6a974cb06a08d08d6188656d8908ef65c62f2e76 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 10:46:56 +0200 Subject: [PATCH 11/66] ru/essentials/named-views.md ru translation --- docs/ru/essentials/named-views.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/ru/essentials/named-views.md b/docs/ru/essentials/named-views.md index 8a78c5a9e..316f200dd 100644 --- a/docs/ru/essentials/named-views.md +++ b/docs/ru/essentials/named-views.md @@ -1,6 +1,6 @@ -# Named Views +# Именованные представления -Sometimes you need to display multiples 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. +Иногда необходимо отобразить сразу несколько компонентов, не вкладывая их один в другой — например, при создании разметки с сайдбаром и основным контентом. В этой ситуации может быть удобно использовать именованные представления. Вместо указания единственного ``, можно использовать несколько, присвоив каждому имя. Безымянный `router-view` автоматически получает имя `default`. ``` html @@ -8,8 +8,7 @@ Sometimes you need to display multiples views at the same time instead of nestin ``` -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 -an s) option: +При использовании нескольких представлений, вместо единственного компонента при описании пути необходимо указывать объект. Удостоверьтесь, что используете окончание множественного числа (s) в ключе `components`: ``` js const router = new VueRouter({ @@ -26,5 +25,4 @@ const router = new VueRouter({ }) ``` -A working demo of this example can be found -[here](https://jsfiddle.net/posva/6du90epg/). +Рабочее демо этого примера можно найти [здесь](https://jsfiddle.net/posva/6du90epg/). From 222dd2ced62b2ab13a3b944e29c6aafd40cedce1 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 10:56:58 +0200 Subject: [PATCH 12/66] ru/essentials/redirect-and-alias.md ru translation --- docs/ru/essentials/redirect-and-alias.md | 30 ++++++++++++------------ 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/ru/essentials/redirect-and-alias.md b/docs/ru/essentials/redirect-and-alias.md index b23aa95d7..9c1698476 100644 --- a/docs/ru/essentials/redirect-and-alias.md +++ b/docs/ru/essentials/redirect-and-alias.md @@ -1,8 +1,8 @@ -# Redirect and Alias +# Редиректы и псевдонимы -### Redirect +### Редирект -Redirecting is also done in the `routes` configuration. To redirect from `/a` to `/b`: +Редиректы также определяются в конфигурации путей `routes`. Для редиректа с `/a` на `/b`, укажите: ``` js const router = new VueRouter({ @@ -12,7 +12,7 @@ const router = new VueRouter({ }) ``` -The redirect can also be targeting a named route: +В качестве цели редиректа можно использовать и именованный путь: ``` js const router = new VueRouter({ @@ -22,28 +22,28 @@ const router = new VueRouter({ }) ``` -Or even use a function for dynamic redirecting: +Можно даже указать функцию для организации динамического редиректа: ``` js const router = new VueRouter({ routes: [ - { path: '/a', redirect: to => { - // the function receives the target route as the argument - // return redirect path/location here. + { path: '/a', redirect: to => { + // в функцию в качестве аргумента передаётся путь + // возвращаемым значением должна быть строка или объект пути }} ] }) ``` -For other advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js). +Для демонстрации более сложных возможностей, обратите внимание на [этот пример](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js). -### Alias +### Псевдонимы -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? +При редиректе, если пользователь переходит по пути `/a`, URL заменяется на `/b` и затем уже `/b` рассматривается как основной путь. В чём отличие псевдонима? -**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`.** +**В случае, когда псевдонимом `/a` является `/b`, при посещении пользователем `/b` URL останется равным `/b`, но роутер выполнит все действия так, как если бы он был равен `/a`.** -The above can be expressed in the route configuration as: +В виде конфигурации роутера вышесказанное может быть выражено так: ``` js const router = new VueRouter({ @@ -53,6 +53,6 @@ const router = new VueRouter({ }) ``` -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. +Псевдонимы позволяют не ограничиваться вложенными структурами при организации связи URL и UI. -For advanced usage, checkout the [example](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js). +Этот [пример](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js) демонстрирует более продвинутое использование возможностей. From a3c31bd389ef4f2e68557772a0768c4fe2c0a747 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 11:09:24 +0200 Subject: [PATCH 13/66] ru/essentials/history-mode.md ru translation --- docs/ru/essentials/history-mode.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/ru/essentials/history-mode.md b/docs/ru/essentials/history-mode.md index 56c55ffdc..c057a1afe 100644 --- a/docs/ru/essentials/history-mode.md +++ b/docs/ru/essentials/history-mode.md @@ -1,8 +1,8 @@ -# HTML5 History Mode +# Режим HTML5 History -The default mode for `vue-router` is _hash mode_ - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. +Режимом по умолчанию для `vue-router` является _hash mode_ — для симуляции полного URL в этом случае используется хэш, что позволяет избежать перезагрузки страницы при изменении URL. -To get rid of the hash, we can use the router's **history mode**, which leverages the `history.pushState` API to achieve URL navigation without a page reload: +Мы можем обойтись без этого костыля, используя **history mode**, основывающийся на API `history.pushState` для достижения той же цели: ``` js const router = new VueRouter({ @@ -11,13 +11,13 @@ const router = new VueRouter({ }) ``` -When using history mode, the URL will look "normal," e.g. `http://oursite.com/user/id`. Beautiful! +При использовании history mode, URL выглядят совершенно "нормально": например, `http://oursite.com/user/id`. Не прекрасно ли? -Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access `http://oursite.com/user/id` directly in their browser. Now that's ugly. +Возникает, однако, и проблема: поскольку наше приложение — одностраничное, не сконфигурировав соответствующим образом сервер мы заставим пользователей получать ошибку 404, если они перейдут по `http://oursite.com/user/id` напрямую. Вот это уже прекрасным не назвать. -Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same `index.html` page that your app lives in. Beautiful, again! +Не спешите расстраиваться: всё, что нужно — единственная "резервная" запись в конфигурации сервера. Если URL не совпадает ни с одним статическим файлом, сервер должен просто отдать `index.html`, в котором и живёт наше приложение. Красота возвращена! -## Example Server Configurations +## Примеры конфигурации серверов #### Apache @@ -42,11 +42,11 @@ location / { #### Node.js (Express) -For Node.js/Express, consider using [connect-history-api-fallback middleware](https://github.com/bripkens/connect-history-api-fallback). +При использовании Node.js/Express, мы рекомендуем пользоваться [connect-history-api-fallback middleware](https://github.com/bripkens/connect-history-api-fallback). -## Caveat +## Предостережение -There is a caveat to this: Your server will no longer report 404 errors as all not-found paths now serve up your `index.html` file. To get around the issue, you should implement a catch-all route within your Vue app to show a 404 page: +При таком подходе возникает одно неприятное последствие: сервер больше не будет выдавать ошибки 404, так как обслуживание всех путей отдаётся на откуп клиентскому роутингу. Частично эту проблему можно решить, указав путь по умолчанию во vue-router: ``` js const router = new VueRouter({ @@ -57,4 +57,4 @@ const router = new VueRouter({ }) ``` -Alternatively, if you are using a Node.js server, you can implement the fallback by using the router on the server side to match the incoming URL and respond with 404 if no route is matched. +Если же вы используете на сервере Node.js, уже на стороне сервера можно задействовать конфигурацию роутера и решить таким образом проблему целиком. From 9ff6f89c0532bedf95ff21b96ed11db409b23c80 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 14:24:44 +0200 Subject: [PATCH 14/66] ru/advanced/navigation-guards.md translation --- docs/ru/advanced/navigation-guards.md | 58 +++++++++++++-------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/docs/ru/advanced/navigation-guards.md b/docs/ru/advanced/navigation-guards.md index 4a36ae1a3..5f649b830 100644 --- a/docs/ru/advanced/navigation-guards.md +++ b/docs/ru/advanced/navigation-guards.md @@ -1,10 +1,10 @@ -# Navigation Guards +# Сторожевые хуки -As the name suggests, the navigation guards provided by `vue-router` are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component. +Как следует из названия, сторожевые хуки `vue-router` используются для редиректов или отмены навигационных переходов. Есть несколько способов внедрить сторожевой хук: глобально, для конкретного пути, или для конкретного компонента. -### Global Guards +### Глобальные хуки -You can register global before guards using `router.beforeEach`: +Глобальный хук можно зарегистрировать через `router.beforeEach`: ``` js const router = new VueRouter({ ... }) @@ -14,25 +14,26 @@ router.beforeEach((to, from, next) => { }) ``` -Global before guards are called in creation order, whenever a navigation is triggered. Guards may be resolved asynchronously, and the navigation is considered **pending** before all hooks have been resolved. +Глобальные сторожевые хуки вызываются в порядке создания при каждом навигационном переходе. Допускается асинхронное разрешение хуков — в этом случае переход считается **незавершённым** до тех пор, пока не будут разрешены все хуки. -Every guard function receives three arguments: +В каждый сторожевой хук передаётся три параметра: -- **`to: Route`**: the target [Route Object](../api/route-object.md) being navigated to. +- **`to: Route`**: целевой [объект Route](../api/route-object.md), к которому осуществляется переход. -- **`from: Route`**: the current route being navigated away from. +- **`from: Route`**: текущий путь, с которого осуществляется переход к новому. - **`next: Function`**: this function must be called to **resolve** the hook. The action depends on the arguments provided to `next`: +- **`next: Function`**: функция, вызов которой **разрешает** хук. В зависимости от переданных в `next` аргументов, результатом будет: - - **`next()`**: move on to the next hook in the pipeline. If no hooks are left, the navigation is **confirmed**. + - **`next()`**: переход к следующему хуку в цепочке. Если хуков больше нет, переход считается **подтверждённым**. - - **`next(false)`**: abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the `from` route. + - **`next(false)`**: отмена перехода. Если URL был изменён (вручную пользователем, или кнопкой "назад"), он будет сброшен на соответствующий пути `from`. - - **`next('/')` or `next({ path: '/' })`**: redirect to a different location. The current navigation will be aborted and a new one will be started. + - **`next('/')` or `next({ path: '/' })`**: редирект на другой путь. Текущий переход будет отменён, и процесс начнётся заново для нового пути. -**Make sure to always call the `next` function, otherwise the hook will never be resolved.** +**Удостоверьтесь, что функция `next` так или иначе будет вызвана, иначе хук никогда не будет разрешён.** -You can also register global after hooks, however unlike guards, these hooks do not get a `next` function and cannot affect the navigation: +Можно также зарегистрировать глобальные хуки, вызываемые после завершения перехода. Однако, в отличие от сторожевых хуков, в них не передаётся функция `next`, и на ход перехода они повлиять не могут: ``` js router.afterEach((to, from) => { @@ -40,9 +41,9 @@ router.afterEach((to, from) => { }) ``` -### Per-Route Guard +### Указание хука для конкретного пути -You can define `beforeEnter` guards directly on a route's configuration object: +Сторожевые хуки `beforeEnter` можно указать напрямую для конкретного пути в его конфигурации: ``` js const router = new VueRouter({ @@ -58,38 +59,37 @@ const router = new VueRouter({ }) ``` -These guards have the exact same signature as global before guards. +Эти хуки ничем не отличаются от глобальных. -### In-Component Guards +### Указание хука для конкретного компонента -Finally, you can directly define route navigation guards inside route components with `beforeRouteEnter` and `beforeRouteLeave`: +Наконец, сторожевой хук можно указать и непосредственно в компоненте, используя `beforeRouteEnter` и `beforeRouteLeave`: ``` js const Foo = { template: `...`, beforeRouteEnter (to, from, next) { - // called before the route that renders this component is confirmed. - // does NOT have access to `this` component instance, - // because it has not been created yet when this guard is called! + // вызывается до подтверждения пути, соответствующего этому компоненту. + // НЕ ИМЕЕТ доступа к контексту инстанса компонента `this`, + // так как к моменту вызова истанс ещё не создан! }, - beforeRouteLeave (to, from, next) { - // called when the route that renders this component is about to - // be navigated away from. - // has access to `this` component instance. + beforeRouteLeave (to, from, next) { + // вызывается перед переходом от пути, соответствующего текущему компоненту; + // имеет доступ к контексту инстанса компонента `this`. } } ``` -The `beforeRouteEnter` guard does **NOT** have access to `this`, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet. +Хук `beforeRouteEnter` **НЕ ИМЕЕТ** доступа к `this`, так как к моменту его вызова навигация ещё не подтверждена, а значит и инстанс компонента ещё не создан. -However, you can access the instance by passing a callback to `next`. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument: +Тем не менее, доступ к инстансу можно получить, передав коллбэк в `next`. Эта функция будет вызвана после подтверждения навигации, а экземпляр компонента будет передан в неё в качестве параметра: ``` js beforeRouteEnter (to, from, next) { next(vm => { - // access to component instance via `vm` + // инстанс компонента доступен как `vm` }) } ``` -You can directly access `this` inside `beforeRouteLeave`. The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by calling `next(false)`. +Внутри `beforeRouteLeave` можно обращаться к `this` напрямую. Этот сторожевой хук обычно используется для предотвращения случайного ухода пользователя с пути, содержащего несохранённые отредактированные данные. Переход можно отменить, вызвав `next(false)`. From 469e7f760af24701487e9ecc9e6ada4303cd14c3 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 14:32:22 +0200 Subject: [PATCH 15/66] ru/advanced/meta.md translation --- docs/ru/advanced/meta.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/ru/advanced/meta.md b/docs/ru/advanced/meta.md index 79845b28d..76db4c86c 100644 --- a/docs/ru/advanced/meta.md +++ b/docs/ru/advanced/meta.md @@ -1,6 +1,6 @@ -# Route Meta Fields +# Метаданные путей -You can include a `meta` field when defining a route: +При определении пути можно указывать метаданные в поле `meta`: ``` js const router = new VueRouter({ @@ -12,7 +12,7 @@ const router = new VueRouter({ { path: 'bar', component: Bar, - // a meta field + // метаданные meta: { requiresAuth: true } } ] @@ -21,21 +21,21 @@ const router = new VueRouter({ }) ``` -So how do we access this `meta` field? +Как получить к нему доступ? -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. +Прежде всего, каждый объект пути в конфигурации `routes` называется **записью пути**. Записи путей могут быть вложенными. Поэтому, при совпадении пути, потенциально могут быть активированы несколько записей путей. -For example, with the above route config, the URL `/foo/bar` will match both the parent route record and the child route record. +Например, для конфигурации выше, URL `/foo/bar` совпадёт как с родительской, так и с дочерней записями путей. -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. +Все совпавшие записи путей оказываются доступны через объект `$route` (а также через объекты пути в сторожевых хуках), в виде массива `$route.matched`. Таким образом, для проверки метаданных в записях путей нам понадобиться обойти `$route.matched` в цикле. -An example use case is checking for a meta field in the global navigation guard: +В качестве примера можно привести проверку метаданных в глобальном сторожевом хуке: ``` js router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { - // this route requires auth, check if logged in - // if not, redirect to login page. + // этот путь требует авторизации, проверяем залогинен ли + // пользователь, и если нет, перенаправляем на страницу логина if (!auth.loggedIn()) { next({ path: '/login', @@ -45,7 +45,7 @@ router.beforeEach((to, from, next) => { next() } } else { - next() // make sure to always call next()! + next() // всегда так или иначе нужно вызвать next()! } }) ``` From dad4bc58b1fd9e397de7d179f84ab2099ce05cca Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 14:40:03 +0200 Subject: [PATCH 16/66] ru/advanced/transitions.md translation --- docs/ru/advanced/transitions.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/ru/advanced/transitions.md b/docs/ru/advanced/transitions.md index d6595b23b..51f067bd3 100644 --- a/docs/ru/advanced/transitions.md +++ b/docs/ru/advanced/transitions.md @@ -1,6 +1,6 @@ -# Transitions +# Анимация переходов -Since the `` is essentially a dynamic component, we can apply transition effects to it the same way using the `` component: +Поскольку `` — это просто динамический компонент, к нему можно применить анимированные переходы, используя ``: ``` html @@ -8,11 +8,11 @@ Since the `` is essentially a dynamic component, we can apply trans ``` -[Everything about ``](http://vuejs.org/guide/transitions.html) works the same here. +[Всё, что сказано о `` в основной документации](http://vuejs.org/guide/transitions.html) применимо и здесь. -### Per-Route Transition +### Анимация переходов для конкретных путей -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: +Синтаксис выше применит одну и ту же анимацию перехода для всех путей. Если для различных путей хочется указать разные анимационные эффекты, можно использовать разноимённые `` непосредственно в шаблонах компонентов: ``` js const Foo = { @@ -32,20 +32,21 @@ const Bar = { } ``` -### Route-Based Dynamic Transition +### Динамические анимационные переходы для путей -It is also possible to determine the transition to use dynamically based on the relationship between the target route and current route: +Можно также определить переходы для путей динамически, в зависимости от соотношения между старым и новым путём: ``` html - + ``` ``` js -// then, in the parent component, -// watch the $route to determine the transition to use +// затем, в родительском компоненте, будем следить за переменной $route, +// чтобы определить, какой анимационный переход применить + watch: { '$route' (to, from) { const toDepth = to.path.split('/').length @@ -55,4 +56,4 @@ watch: { } ``` -See full example [here](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). +Полный пример можно посмотреть [здесь](https://github.com/vuejs/vue-router/blob/dev/examples/transitions/app.js). From c51a251f105e4ef3622fb93ac5e9077fe2350e71 Mon Sep 17 00:00:00 2001 From: Grigoriy Beziuk Date: Mon, 28 Nov 2016 14:54:40 +0200 Subject: [PATCH 17/66] ru/advanced/data-fetching.md translation --- docs/ru/advanced/data-fetching.md | 38 +++++++++++++++---------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/docs/ru/advanced/data-fetching.md b/docs/ru/advanced/data-fetching.md index aa520b1c5..362965b67 100644 --- a/docs/ru/advanced/data-fetching.md +++ b/docs/ru/advanced/data-fetching.md @@ -1,18 +1,18 @@ -# Data Fetching +# Запросы данных -Sometimes you need to fetch data from the server when a route is activated. For example, before rendering a user profile, you need to fetch the user's data from the server. We can achieve this in two different ways: +Нередко при переходе между путями требуется получить от сервера какие-либо данные. Например, перед отображением профиля пользователя, нужно запросить данные о нём. Этой цели можно достичь двумя различными путями: -- **Fetching After Navigation**: perform the navigation first, and fetch data in the incoming component's lifecycle hook. Display a loading state while data is being fetched. +- **Запросив данные после перехода**: сначала перейти к новому пути, затем запросить данные в хуке жизненного цикла целевого компонента. По мере загрузки данных отобразить индикатор состояния загрузки. -- **Fetching Before Navigation**: Fetch data before navigation in the route enter guard, and perform the navigation after data has been fetched. +- **Запросив данные перед переходом**: запросить данные в сторожевом хуке роутера, и завершить навигацию уже по когда они будут получены. -Technically, both are valid choices - it ultimately depends on the user experience you are aiming for. +С технической точки зрения, оба способа годятся — выбор зависит от того, какой UX вы хотите получить. -## Fetching After Navigation +## Запрос данных после перехода -When using this approach, we navigate and render the incoming component immediately, and fetch data in the component's `created` hook. It gives us the opportunity to display a loading state while the data is being fetched over the network, and we can also handle loading differently for each view. +При использовании этого подхода, мы осуществляем переход и рендеринг целевого компонента сразу же, а данные запрашиваем в хуке `created` компонента. Это позволяет нам отобразить состояние загрузки, пока данные загружаются по сети, и сделать это различным образом для различных компонентов. -Let's assume we have a `Post` component that needs to fetch the data for a post based on `$route.params.id`: +Предположим, у нас есть компонент `Post`, которому требуется загрузить с сервера данные, соответствующие id поста из `$route.params.id`: ``` html