Vue practice is essential to note (8) - Vue Router

  Although Vue.js not provide routing capabilities, but the official launch of the Vue Router (ie vue-router Library), support in the form of plug-ins. It is integrated with Vue.js depth, you can quickly create a single-page application (Single Page Application, SPA).

First, the basic usage

  First need to introduce vue vue-router and two libraries, such as if the global referenced below (that is, there is a global variable Vue), then vue-router will automatically call Vue.use () method to register itself; but if by way of reference to the module then you have to explicitly call Vue.use ().

<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>

  Then add two built-in components, a first component is a router-link for navigation, which will be rendered by default <a> elements, if rendered into other elements, then it may be used to tag attributes; the second is router-view assembly for rendering views when path matching, it is a functional component, as shown below.

<div id="container">
  <router-link to="/main">首页</router-link>
  <router-link to="/list">列表</router-link>
  <router-view></router-view>
</div>

  And then declare the components to be rendered, these components will be mapped to the specified route, here are two very simple custom components.

const Main = {template: '< div> Home </ div>' }; 
const List = {Template: '<div> list </ div>'};

  It then defines routing configuration, add a set of paths and the corresponding components, as shown below.

const routes = [
  { path: '/main', component: Main },
  { path: '/list', component: List }
];

  Finally, create a router instance, the routing configuration and passed in before, when mounting root instance, it needs to be injected, so that the whole application has a routing function, as shown below.

const router = new VueRouter({
  routes: routes
});
var vm = new Vue({
  el: "#container",
  router: router
});

  Note that, router instance three navigation method comprising: push (), replace (), and go (), navigation may be performed programmatically.

  Page rendering is complete, the resulting DOM structure is shown below, router-view case assembly position occupied without any content.

<div id="container">
  <a href="#/main" class="">首页</a>
  <a href="#/list" class="">列表</a>
</div>

  When the router-link assembly corresponding routing successfully matched, which render the element will be automatically added a CSS class: router-link-active. Such as clicking home link, as shown, note that the resulting structure is as follows, when components are replaced router-view content became Main components.

<div id="container">
  <a href="#/main" class="router-link-active">首页</a>
  <a href="#/list" class="">列表</a>
  <div>首页</div>
</div>

Second, routing mode

  Vue Router defaults URL hash mode to keep the URL of the page and synchronization, it creates URL format needs to contain a pound sign (#), as shown below.

http://pwstrick.com/#/main

  Vue Router mode there is another history, the use of HTML5 History to keep pace and the URL of the page, URL format that creates visually more simple and clear, as shown below.

http://pwstrick.com/main

  If you want to turn history mode, you need to add in the routing configuration mode option, and given history keyword, as follows (directly modify the example in the previous section).

const router = new VueRouter({
  mode: "history",
  routes: routes
});

  Note that when direct access to the history mode created URL, will return to a 404 page. To prevent this from happening, we recommend a default on the server configuration candidate page.

Third, routing

  This section will not only introduce the concept of dynamic routing, routing analysis will be named and nested operations.

1) Dynamic Routing

  Vue Router Path matching engine uses a path-to-regexp, which supports dynamic routing to match, for example, a List component, the parameters need to page the path component up into different contents can be configured as follows.

const List = { template: '<div>{{$route.params.page}}</div>' };
const routes = [
  { path: '/list/:page', component: List }
];

  In routing configuration, beginning with a colon: page parameter is the path, its value will be saved to the params property $ route in the route object. Routing object contains not only information (e.g. path, the query string, anchor, etc.) parse the URL obtained, as well as the matching routing information (e.g., name the route, routing, etc). When the path is / list / 1 when, $ route.params values ​​{page: 1}, params is an object that the key corresponding to the path parameters. Note that the path may comprise a plurality of paths of different parameters.

  When a plurality of route paths can be matched, the matching priority of the route according to the order defined rows, i.e., the first definition, a high priority. The following configuration contains two routes, when the path is / list / 1, the assembly will render List.

const routes = [
  { path: '/list/:page', component: List },
  { path: '/list/1', component: Main }
];

2) Name Route

  A name for the route may be identified during the configuration, so the path can be omitted, as shown below, is the route name attribute value in use.

const routes = [
  { path: '/list/:page', component: List, name: "list" }
];

  If you want to navigate to a named route, you need to dynamically bind to property, and its passing in the name of the route, and optional URL parameters, as shown below.

<router-link :to="{ name: 'list', params: {page: 3} }">第三页</router-link>

3) route Nested

  Vue Router allows nested routing can be achieved by nested components. Here is an example, the first statement router-view view of a component assembly, as shown below.

const List = { template: '<router-view></router-view>' };
const Detail = { template: '<div>详情</div>' };

  Then in the routing configuration, the option to add children and define sub-routes.

const routes = [
  {
    path: "/list",
    component: List,
    children: [{ path: "detail", component: Detail }]
  }
];

  After this series of operations, when the path is / list / detail when, the component will be rendered to the Detail List view assembly.

  Nested route can be used to render the view of a plurality of different levels, and a plurality of views using the named view may be rendered at the same level. In the following code, is added as a second router-view component name attribute, gives it a name, a first name and a default router-view assembly is default.

<router-view></router-view>
<router-view name="detail"></router-view>

  When routing configuration, new options for recording the individual components of the named components, as shown below.

const routes = [
  {
    path: "/named",
    components: {
      default: Main,
      detail: Detail
    }
  }
];

  When the path is / named when, Main and Detail two components are rendered simultaneously.

Fourth, and redirect alias

1) Redirect

  In the routing configuration by redirect option to redirect to a new page, which option has three possible values, namely the path, name and callback routing, as shown below, to the parameters of the function represents the target route object.

const routes = [
  { path: "/list/1", redirect: "/main" },
  { path: "/list/1", redirect: {name: "main"} },
  { path: "/list/1", redirect: to => "/main" }
];

  When the access path is / list / 1, the address bar of the browser will become / main, the match will be the path / main route.

2) Alias

  In the routing configuration by alias alias option to define the routing, as shown below.

const routes = [
  { path: "/list/4", component: Detail, alias: "/detail" }
];

  When the path is accessible / main, the address bar of the browser remains / main, but the match will be the path routing / list / 4 in.

Five components of mass participation

  In addition to obtaining routing parameters $ route.params outside the assembly, but also the routing parameters as props incoming assembly, thereby decoupling assembly and routing, as shown below.

const List = {
  props: ["page"],
  template: "<div>{{page}}</div>"
};
const routes = [
  { path: "/list/:page", component: List, props: true }
];

  It should be noted that, in the routing configuration options to add props, and after giving true, will make routing parameters and associated props.

Six guards navigation

  Navigation is guarding the hook function when the route changes, Vue Router provides three types of guards: global, exclusive routing and component level.

1) Global guards

  Examples which may be registered in the three global router guards, respectively beforeEach (), beforeResolve () and afterEach ().

  beforeEach () is a global front guard, comprising three parameters (see below), where the goal is to route the object, from a source routing target, next is a callback function for parsing (Resolve) current guard.

router.beforeEach((to, from, next) => {
  next();
});

  Since the navigation parsing until all guards would be in a wait state (i.e., the path does not change, it does not render the corresponding components), and therefore can not be omitted in the callback next () function. Note that this function can not only deal with navigation, but also to interrupt or redirect, even registered a mistake.

  beforeResolve () is a global analytical guard, and its parameters beforeEach () is the same as before the navigation is confirmed, and guarding and asynchronous routing components within the assembly after the call is resolved. afterEach () is a global home after the guard, it is only to and from the two parameters.

2) routing guard

  In the routing configuration can be defined directly beforeEnter () guard, acting on a global rather than a separate route, and the same parameters which beforeEach (), as shown below.

const routes = [
  {
    path: "/list",
    component: List,
    beforeEnter: (to, from, next) => {
      next();
    }
  }
];

3) Components guard

  Navigation within the guard assembly comprises three, listed below, are () parameters and their same beforeEach, but also to, from, and next.

  (1) beforeRouteEnter (): Because this component is called before the navigation confirm, therefore the component has not yet been created, so this can not get access component instance. However, next () function can receive a callback parameter component instance, as shown below.

List = const { 
  beforeRouteEnter: function (to, from, Next) { 
    Next (VM => { 
       // VM component instance 
    }); 
  } 
};

  (2) beforeRouteUpdate (): can be obtained by the this component instance, when a route changes, but a multiplexed component will call the guard. For example, a path / list /: Routing page (shown below configuration), when the / list / 1 to navigate list / 2, since the rendering List component are, therefore calls beforeRouteUpdate () guard.

const routes = [
  {
    path: "/list/:page",
    component: List
  }
];

  (3) beforeRouteLeave (): this can be obtained by a component instance, when the route change, and the rendering component is not the same, will call the guard. For example, there are two paths / main and / list, and List Main components respectively, declares beforeRouteLeave component in List () guard (below), when viewed from / list to navigate / main, confirmation box will pop up, is determined the need to cancel the navigation.

const List = {
  beforeRouteLeave: function(to, from, next) {
    const answer = window.confirm("是否离开当前页?");
    answer ? next() : next(false);
  }
};

4) the resolution process

  Complete navigation parsing process are listed below.

(1) navigation is triggered.

(2) call beforeRouteLeave in inactivation of components in () guard.

(3) calls global beforeEach () guard.

(4) calls beforeRouteUpdate in reusable components in () guard.

(5) calls beforeEnter () guards in the routing configuration.

(6) Analysis asynchronous routing components.

(7) calls beforeRouteEnter () guarding the activated components inside.

(8) calls the global beforeResolve () guard.

(9) is a navigation acknowledgment.

(10) calls global afterEach () guard.

(11) triggered DOM updates.

(12) with a call to create a good example beforeRouteEnter (guard in the next parameter passed to the callback function).

 

Guess you like

Origin www.cnblogs.com/strick/p/11495419.html