MEMEPh. ideas that are worth sharing...

Learn vue-router from scratch

1. Introduction


To learn vue-router, you must first know what the routing here is? Why can't we write links directly with tags like we used to? How to use vue-router? What are the common routing operations? These issues, etc., are the main issues to be discussed in this article.

 

2. What is vue-router


The routing here does not refer to the hardware routers that we usually refer to. The routing here is the path manager of the SPA (single page application) . In layman's terms, vue-router is the link path management system of WebApp.
vue-router is the official routing plugin for Vue.js. It is deeply integrated with vue.js and is suitable for building single-page applications. Vue's single-page application is based on routing and components. Routing is used to set access paths and map paths and components. In traditional page applications, some hyperlinks are used to achieve page switching and jumping. In the vue-router single-page application, it is the switching between paths, that is, the switching of components. The essence of the routing module is to establish the mapping relationship between the url and the page.

As for why we can't use the a tag, this is because all single-page applications are made with Vue ( when your project is ready to be packaged and run npm run build, a dist folder will be generated, which only contains static resources and an index.html page ), so the tags you write won't work, you have to use vue-router to manage them.

 

3. vue-router implementation principle


SPA (single page application): A single page application with only one complete page; when loading a page, it will not load the entire page, but only update the content in a specified container. One of the cores of single-page application (SPA) is: update the view without re-requesting the page; vue-router provides two ways when implementing single-page front-end routing: Hash mode and History mode; whichever is used depends on the mode parameter. a method.

 

1. Hash mode:

vue-router default hash mode - uses the URL hash to simulate a full URL, so when the URL changes, the page doesn't reload. Hash (#) is the anchor point of the URL, which represents a position in the web page. If the part after # is changed, the browser will only scroll to the corresponding position and will not reload the web page, which means that the hash appears in the URL. But it will not be included in the http request and has no effect on the backend at all, so changing the hash will 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, using "back" " button, you can go back to the previous position; so the Hash mode renders different data of the specified DOM position according to the change of the anchor value according to different values. The principle of the hash mode is the onhashchange event (monitoring the hash value change), which can be monitored on the window object .

 

2. History mode:

Since the hash mode will have its own # in the url, if we don't want ugly hash, we can use the history mode of routing, just add "mode: 'history'" when configuring routing rules, this mode makes full use of The new pushState() and replaceState() methods in the html5 history interface. These two methods are applied to the browser record stack. Based on the current back, forward, and go, they provide the function of modifying the history record. It's just that when they perform modifications, although the current URL is changed, the browser doesn't immediately send a request to the backend.

//main.js
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

When you use history mode, the URL is like a normal url, like http://yoursite.com/user/id, which is nicer!
However, in order to play this mode well, it also needs background configuration support. Because our application is a single-page client application, if the background is not properly configured, when the user directly accesses http://oursite.com/user/id in the browser, it will return 404, which is not good.
So, you need to add a candidate resource that covers all situations on the server side: if the URL does not match any static resources, it should return the same index.html page, which is the page your app depends on.

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

Here it is set that if the URL is entered incorrectly or the URL does not match any static resources, it will automatically jump to the Home page

 

3. Use the routing module to achieve page jumping

 

4. How to use vue-router


1: Download npm i vue-router -S
2: Introduce in main.js import VueRouter from 'vue-router';
3: Install the plugin Vue.use(VueRouter);
4: Create a routing object and configure routing rules let router = new VueRouter({routes:[{path:'/home',component:Home}]});
5: Pass its routing object to the instance of Vue, add it to options router:router
6: Leave it in app.vue pit <router-view></router-view>

For specific implementation, please see the following code:

//Introduced in the main.js file
import Vue from 'vue';
import VueRouter from 'vue-router';
//main body
import App from './components/app.vue';
import Home from './components/home.vue'
//install plugin
Vue.use(VueRouter); //Mount properties
//Create a routing object and configure routing rules
let router = new VueRouter({
routes: [
// an object
{ path: '/home', component: Home }
]
});
//new Vue start
new Vue({
el: '#app',
//Let vue know our routing rules
router: router, // can be abbreviated as router
render: c => c(App),
})

 

Finally, remember to "leave a pit" in app.vue


//app.vue
<template>
<div>
<!-- Keep the pit, very important -->
<router-view></router-view>
</div>
</template>
<script>
export default {
data(){
return {}
} 
} 
</script>

 

5. vue-router parameter transmission


Both declarative navigation <router-link :to="..."> and programmatic navigation router.push(...)can pass parameters. This article mainly introduces the method of passing parameters for the former. The same rules apply to programmatic navigation.

 

1. Pass parameters with name

Configure the name attribute in the routing file src/router/index.js

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

The template (src/App.vue) is $route.name used to receive for example:<p>{{ $route.name}}</p>

 

2 <router-link>Pass parameters through to in the tag

The basic syntax of this parameter passing method:

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

For example, first in the src/App.vue file

<router-link :to="{name:'hi1',params:{username:'jspang',id:'555'}}">Hi page 1</router-link>

Then give a name to the route configured by hi1 in the src/router/index.js file, which is called hi1.

{path:'/hi1',name:'hi1',component:Hi1}

Finally, it is received in the template (src/components/Hi1.vue) $route.params.username.

{{$route.params.username}}-{{$route.params.id}}


3 Use url to pass parameters----set parameters in the form of colons in the configuration file.

We configure routing in the /src/router/index.js file

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

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

Create our params.vue component in the src/components directory, which can also be said to be a page. We output the news ID and news title passed by the url in the page.

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

Add our <router-view> tag to the App.vue file. At this time, 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 then pass parameters through query

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

Corresponding routing configuration:

   {
     path: '/query',
     name: 'Query',
     component: Query
   }

So we can get the parameters:

this.$route.query.queryId

 

6. vue-router configuration sub-route (secondary route)


The application interface in real life is usually composed of multiple layers of nested components. Similarly, each segment of the dynamic path in the URL also corresponds to each level of nested components according to a certain structure, for example:

How to achieve the effect of the following figure (H1 page and H2 page are nested in the main page) ?


1. First <router-link> add two new navigation links with labels

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


2. Add <router-view> a tag to HelloWorld.vue to provide an insertion location for the sub-template

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


3. Create two new component templates, H1.vue and H2.vue, in the components directory with similar content. The following is the content of the H1.vue page:

 <template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        msg: 'I am H1 page,Welcome to H1'
      }
    }
  }
</script>


4. Modify the router/index.js code. The sub-route is written by adding the children field to the original routing configuration.

routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
children: [{path: '/h1', name: 'H1', component: H1},//The <router-view> of the child route must appear in HelloWorld.vue
{path: '/h2', name: 'H2', component: H2}
]
} 
]

 

7. single-page multi-routing area operation


We have more than two areas in a page, and we <router-view>operate the content of these areas by configuring the js file of the route

1. App.vue file, <router-view>write two new lines of <router-view>tags below, 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>


2. These three areas need to be configured in the routing, the configuration is mainly done in the components field

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

In the above code, we have written two paths, one is the default '/' and the other is '/Hi'. In the components under the two paths, we define the display content for the three areas. The final page is shown as follows:

 

8. The$route difference between$router


We first print out the two console.logs:

$route is a "routing information object", including routing information parameters such as path, params, hash, query, fullPath, matched, and name.

① A$route.path

string, which corresponds to the path of the current route, is always resolved to an absolute path, such as "/order".

 

② A$route.params

key/value object, including dynamic fragments and full matching fragments,
if there are no routing parameters, it is an empty object.

 

③ $route.query

A key/value object representing URL query parameters.
For example, for the path /foo?user=1, there is $route.query.user of 1,
or an empty object if there are no query parameters.

 

④ $route.hash

The hash value of the current route (without #), if there is no hash value, it is an empty string.

 

⑤ $route.fullPath

Complete the parsed URL, including query parameters and the full path of the hash.

 

⑥ $route.matched

Array, which contains the configuration parameter objects corresponding to all the fragments contained in the currently matched path.

 

⑦ $route.name Current path name

$router is the "route instance" object, that is, the instance created by new VueRouter, including the route jump method, hook function, etc.

Common jump methods of $router:

<button @click="goToMenu" class="btn btn-success">Let's order! </button>
.....
<script>
export default{
methods:{
goToMenu(){
this.$router.go(-1)//Jump to the last page viewed
This.$router.replace('/menu')//Specify the jump address
This.$router.replace({name:'menuLink'})//Under the name of the specified jump route
This.$router.push('/menu')//Jump through push
This.$router.push({name:'menuLink'})//Under the name of the jump route through push
} 
} 
} 
</script>


$router.push and $router.replace the difference :

 

9. How to set up 404 page


Users often enter the wrong page. When the user enters the wrong page, we hope to give him a friendly prompt page. This page is what we often call the 404 page. vue-router also provides us with such a mechanism.

1. Set up our routing configuration file (/src/router/index.js)

{
   path:'*',
   component:Error
}

The path:'*' here means that when the input address does not match, the file content of Error.vue is automatically displayed

Create a new Error.vue file in the /src/components/ folder. Simply type something about the error page.

<template>
    <div>
        <h2>{{ msg }}</h2>
    </div>
</template>
<script>
export default {
  data () {
    return {
      msg: 'Error:404'
    }
  }
}
</script>

At this point, when we arbitrarily enter a wrong address, it will automatically jump to the 404 page