One, foreword

To learn vue-router, you need to know what is the route here? Why can’t we just write links with tags like we used to? How to use vue-router? What are common routing operations? And so on these questions, is the main issue to discuss.

What is vue-router

The routing here is not a hardware router as we normally call it, the routing here is a SPA (single page application) path manager. More commonly, vue-Router is the link path management system of WebApp. Vue-router is the official routing plug-in of vue.js. It is deeply integrated with vue.js and suitable for building single-page applications. The single-page application of VUE is based on routing and components, which are used to set access paths and map paths to components. The traditional page application uses some hyperlinks to realize the page switch and jump. In vue-Router single-page applications, it is switching between paths, that is, switching between components. The essence of routing module is to establish the mapping between URL and page.

As for why we can’t use the A tag, it’s because Vue is a single page app (when you run the NPM Run build when your project is ready to be packaged, the dist folder is generated, which contains only static resources and an index.html page), so the tag you write won’t work. You must use vue-router for administration.

Iii. Vue-router implementation principle

SPA(Single Page Application): a single page application with only one complete page; When it loads a page, it does not load the entire page, but only updates the contents of a specified container. One of the core aspects of a single page application (SPA) is updating a view without rerequesting the page; Vue-router implements single-page front-end routing in Hash mode and History mode. The mode parameter determines which mode to use.

1. Hash mode:

Vue-router defaults to hash mode — the hash of a URL is used to simulate a full URL so that the page does not reload when the URL changes. Hash (#) is the anchor point of the URL, which represents a location in the web page. Simply changing the part after the #, the browser will scroll to that location instead of reloading the web page. This means that the hash appears in the URL, but is not included in the HTTP request. So changing the hash does not reload the page; At the same time, every time the part after # is changed, a record will be added to the browser’s access history. Use the “back” button to go back to the previous position. So Hash mode renders different data for the specified DOM position by changing the anchor value. Hash mode is based on the onHashChange event (which monitors hash changes), which can be listened for on the window object.

2. History mode:

Since hash mode has a hash tag attached to the URL, if you don’t want an ugly hash, you can use the history mode of the route. Just add “mode: ‘history'”, which takes advantage of the new pushState() and replaceState() methods in the HTML5 History Interface. These two methods apply to the browser record stack and provide the ability to modify the history in addition to the existing back, Forward, and Go methods. It’s just that when they make changes that change the current URL, the browser doesn’t immediately send requests to the back end.

// const router = new VueRouter({mode:'history',
  routes: [...]
})
Copy the code

When you use history mode, urls like normal urls, such as yoursite.com/user/id, are better… However, this mode to play well, but also need background configuration support. Because our application is a single-page client application, if the background is not properly configured, when the user accesses oursite.com/user/id directly from the browser, it will return 404, which is not pretty. So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app relies on.

 export const routes = [ 
  {path: "/", name: "homeLink", component:Home}
  {path: "/register", name: "registerLink", component: Register},
  {path: "/login", name: "loginLink", component: Login},
  {path: "*", redirect: "/"}]
Copy the code

This is set up to automatically jump to the Home page if the URL is typed incorrectly or does not match any static resources

3. Use the routing module to realize the way of page skipping

  • Method 1: Modify the address bar directly

  • Method 2: this.$router. Push (‘ router ‘)

Iv. Vue-router usage

Import VueRouter from ‘vue-router’; import VueRouter from ‘vue-router’; 3: Install vue.use (VueRouter); Let router = new VueRouter({routes:[{path:’/home’, Component: home}]});

See the following code for concrete implementation:

// import Vue from from main.js'vue';
import VueRouter from 'vue-router'; // Main import App from'./components/app.vue';
import Home from './components/home.vue'Vue.use(VueRouter); // Create a routing object and configure routing rulesletRouter = new VueRouter({routes: [//'/home', component: Home } ] }); // start new Vue({el:'#app'Router: router, // Render router: c => c(App),})Copy the code

Finally remember to “leave a pit” in app.vue

//app.vue <template> <div> <! <router-view></router ></ div> </template> <script>export default {
        data() {return {}
        }
    }
</script>
Copy the code

V. Vue-router parameter transmission

Declarative navigation

and programmatic navigation router.push(…) This article mainly introduces the method of parameter passing of the former. The same rules also apply to programmatic navigation.

1. Pass parameters by name

Configure the name attribute in the route file SRC /router/index.js

routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
]
Copy the code

{{$route.name}}

2 by<router-link>The to parameter in the tag is passed

The basic syntax of this parameter passing method is:

<router-link :to="{name:xxx,params:{key:value}}">valueString</router-link>
Copy the code

For example, in the SRC/app.vue file

<router-link :to="{name:'hi1',params:{username:'jspang',id:'555'}}"Page 1 < / router - link > > HiCopy the code

SRC /router/index.js name the route configured by hi1.

{path:'/hi1',name:'hi1',component:Hi1}
Copy the code

SRC /components/ hi1.vue $route.params.username

{{$route.params.username}}-{{$route.params.id}}
Copy the code

3 Use the URL to pass the parameter —- to set the parameters in the form of colons in the configuration file.

We configure the route in/SRC /router/index.js

{
    path:'/params/:newsId/:newsTitle',
    component:Params
}
Copy the code

The parameters we need to pass are the newsId (newsId) and the newsTitle (newsTitle). So we specify these two values in the routing configuration file.

Create our params.vue component, or page, in the SRC/Components directory. We output the news ID and title of the NEWS delivered by the URL in the page.

<template> <div> <h2>{{MSG}}</h2> <p> News ID: {{$route.params.newsId}}</p> <p>$route.params.newsTitle}}</p>
    </div>
</template>
<script>
export default {
  name: 'params'.data () {
    return {
      msg: 'params page'
    }
  }
}
</script>
Copy the code

Add our

tag to the app. vue file. At this point we can directly use the URL to pass the value

<router-link to="/params/198/jspang website is very good">params</router-link>

4. Use path to match routes and pass parameters through Query

<router-link :to="{ name:'Query',query: { queryId: status }}"> router-link jump Query </router-link>Copy the code

Route configuration:

   {
     path: '/query',
     name: 'Query',
     component: Query
   }
Copy the code

So we can get parameters:

this.$route.query.queryId
Copy the code

Vi. Vue-router Configures child routes (Secondary routes)

Application interfaces in real life are usually composed of several layers of nested components. Similarly, each segment of the dynamic path in the URL also corresponds to nested components of each layer according to a certain structure, for example:

How to achieve the following effect (H1 and H2 pages nested in the home page)?

1. We first added two new navigation links using the

tag

<router-link :to="{name:'HelloWorld'}"> Home </router-link> <router-link :to="{name:'H1'}">H1 </router-link> <router-link :to="{name:'H2'}"> H2 page < / router - the link >Copy the code

2. Add the

tag to helloworld. vue to provide an insert location for the child template

 <template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <router-view></router-view>
  </div>
</template>
Copy the code

3. Create two component templates h1. vue and h2. vue under the Components directory. The contents of the h1. vue page are similar.

 <template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        msg: 'I am H1 page,Welcome to H1'
      }
    }
  }
</script>
Copy the code
  1. Modify the router/index.js code to add the children field to the original route configuration.
   routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      children: [{path: '/h1', name: 'H1', component: H1},// child route <router-view> must appear in helloWorld.vue {path:'/h2', name: 'H2', component: H2}
      ]
    }
  ]
Copy the code

7. Operation of single page and multiple routing areas

We have more than two

areas in one page, and we manipulate the contents of these areas by configuring the js file of the route

1.App.vue file, add two new lines of

tags under

and add some CSS styles

<template>
  <div id="app">
    <img src="./assets/logo.png">
       <router-link :to="{name:'HelloWorld'}"><h1>H1</h1></router-link>
       <router-link :to="{name:'H1'}"><h1>H2</h1></router-link>
    <router-view></router-view>
    <router-view name="left" style="float:left; width:50%; background-color:#ccc; height:300px;"/>
    <router-view name="right" style="float:right; width:50%; background-color:yellowgreen; height:300px;"/>
  </div>
</template>
Copy the code

2. You need to configure the three areas in the Components field

export default new Router({
    routes: [
      {
        path: '/',
        name: 'HelloWorld', components: {default: HelloWorld, left:H1,// Display H1 component contents'I am H1 page,Welcome to H1'Right :H2// Displays the H2 component content'I am H2 page,Welcome to H2'
        }
      },
      {
        path: '/h1',
        name: 'H1', components: {default: HelloWorld, left:H2, right:H1// display H1 component content}}]})Copy the code

In the above code we wrote two paths, one is the default ‘/’ and the other is’ /Hi ‘. In components under both paths, we define display content for all three areas. The final page is shown as follows:

Eight.$route$routerThe difference between

Let’s print both console.log first:

$route is the “routing information object”, including path, Params, Hash, Query, fullPath, matched, name and other routing information parameters.

$route.path indicates the path of the current route. It is always resolved to an absolute path, such as “/order”.

$route.params is a key/value object containing dynamic fragments and fully matched fragments. If there is no route parameter, it is an empty object.

$route.query a key/value object representing the URL query parameter. For example, for path /foo? $route.query.user =1; $route.query.user =1;

④ $route.hash Hash value of the current route (without #). If there is no hash value, it is an empty string.

⑤ $route.fullPath Specifies the parsed URL containing the query parameters and the hash path.

⑥ $route.matched array, which contains configuration parameter objects corresponding to all fragments contained in the current matched path.

All landowners$route.nameCurrent path name

$Router is a “router instance” object, that is, an instance created using new VueRouter. It includes hop methods, hook functions, and so on.

$router

<button @click="goToMenu" class="btn btn-success">Let's order!  ..... /menu$router. Replace ({name:');menuLink'})// Specify the name of the forward route under this.$router.push('/menu$router. Push ({name:')// This.$router. Push ({name:')menuLink}}} Copy the code

$router.push and $router.replace

  • A jump using the push method adds a new record to the history stack, and we see the previous page when we click the browser’s back button.
  • Using the replace method does not add a new record to history, but replaces the current history, meaning that when replace jumps to a page, the back button cannot view the previous page.

How to set up a 404 page

The user will often enter the wrong page, when the user enters the wrong page, we want to give him a friendly prompt page, this page is often referred to as 404 page. Vue-router also provides this mechanism for us.

  1. Set up our route configuration file (/ SRC /router/index.js)
{
   path:The '*',
   component:Error
}
Copy the code

Where path:’*’ is the contents of the Error. Vue file automatically displayed when the input address does not match

  1. Create a new error. vue file in the/SRC /components/ folder. Simply enter something about the error page.
<template>
    <div>
        <h2>{{ msg }}</h2>
    </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'Error:404'
    }
  }
}
</script>
Copy the code

If you enter a wrong address, you will be redirected to a 404 page

Refer to the article

  • Vue-router implements single-page routing
  • Vue.js – Vue-router 60 minutes quick start
  • Technical fat Vue-Router video tutorial
  • The vue$routerAs well as$routeThe use of
  • Vue2.0 Road to Discovery – Vue-Router introductory tutorial and summary
  • Vue-router 2.0 has some differences