Routing actually means pointing. When I click the home button on the page, the home content will be displayed on the page. If I click the about button on the page, the about content will be displayed on the page. Home button => home content, about button => about content, it can also be said to be a mapping. So there are two parts on the page, one is the click part, and the other is the part that displays the content after clicking.
After clicking, how to achieve the correct correspondence? For example, if I click the home button, how can the home content be displayed on the page? This requires configuring the route in the js file.
There are three basic concepts in routing: route, routes, router.
1. route, it is a route, which can also be seen from this English word. It is an singular number. Home button => home content, this is a route, about button => about content, this is another route.
2. routes is a set of routes that combine each route above to form an array. [{home button =>home content }, { about button => about content }]
3. router is a mechanism, equivalent to a manager, which manages routes. Because routes just defines a set of routes, where it is placed is stationary, what should I do when the request is actually coming? What should I do when the user clicks the home button? At this time, the router works. It searches in routes and finds the corresponding home content, so the home content is displayed on the page.
4. The route in the client is actually the display and hiding of the dom element. When the home content is displayed on the page, all the content in about is hidden, otherwise the same is true. There are two implementations of client routing: hash-based and html5 history API.
The routing in vue-router is also implemented based on the above content
Implementing routing in vue is relatively simple. Because all the content on our page is componentized, we just need to correspond to the path and component, and then render the components in the page.
1. Page implementation (in html template)
In vue-router, we see that it defines two tags <router-link> and <router-view> to correspond to the click and display sections. <router-link> is the part that defines the clicked page, and <router-view> defines the display part, which means where the content of the area is displayed after clicking. So <router-link> also has a very important attribute to define where to go after clicking, such as
:<router-link to="/home">Home</router-link>
2. Configure routing in js
First, we need to define route, an implementation of a route. It is an object, composed of two parts: path and component. path refers to the path, and component refers to the component. like
:{path:'/home', component: home}
We have two routes here to form a route:
const routes = [ { path: '/home', component: Home }, { path: '/about', component: About } ]
Finally, create a router to manage the routes, which is created by the constructor new vueRouter(), accepting the routes parameter.
const router = new VueRouter({ routes // routes: abbreviation of routes})
After the configuration is completed, inject the router instance into the vue root instance, and you can use the route
const app = new Vue({ router }).$mount('#app')
Execution process: When the user clicks on the router-link tag, he will look for its to attribute. Its to attribute corresponds to the path configured in js { path: '/home', component: Home} path, thus finding a matching component, and finally rendering the component to the place where the <router-view> tag is located. All of these implementations are based on hash.
vue-cli Create a project to experience it, of course don’t forget to install vue-router
1. Create two new components in the src directory, and
<template> <div> <h1>home</h1> <p>{{msg}}</p> </div> </template> <script> export default { data () { return { msg: "I am a home component" } } } </script> <template> <div> <h1>about</h1> <p>{{aboutMsg}}</p> </div> </template> <script> export default { data () { return { aboutMsg: 'I'm about component' } } } </script>
2, Define <router-link> and </router-view> in
<template> <div > <img src="./assets/"> <header> <!-- router-link Define the path to which click to navigate to --> <router-link to="/home">Home</router-link> <router-link to="/about">About</router-link> </header> <!-- The corresponding component content is rendered torouter-viewmiddle --> <router-view></router-view> </div> </template> <script> export default { } </script>
3. Create a new definition router in the src directory, which is to define the mapping from the path to the component.
import Vue from "vue"; import VueRouter from "vue-router"; // Introduce componentsimport home from "./"; import about from "./"; // Tell vue to use vueRouter(VueRouter); const routes = [ { path:"/home", component: home }, { path: "/about", component: about } ] var router = new VueRouter({ routes }) export default router;
4. Inject the route into the root instance and start the route. There is actually another method here, just like injecting vuex store into the root instance, we can also directly inject vueRouter into the root instance. Introduce routes in and inject them into the root instance.
import Vue from 'vue' import App from './' // Introduce routingimport router from "./" // The router of import router must be lowercase, do not write it as a Router, otherwise it will report an error with can't matchnew Vue({ el: '#app', router, // Inject into the root instance render: h => h(App) })
5. At this time, click home and about on the page to see the components switch back and forth. But there is a problem. When you first enter the page, nothing is displayed in the page. This is because when you first enter the page, its path is '/', and we did not configure this path accordingly. Generally, the home page will be displayed as soon as the page is loaded, and we also need to point this path to the home component. But if we write { path: '/', component: Home }, vue will report an error because the two paths point in the same direction. What to do about this? This requires redirection. The so-called redirection means re-assigning it a direction. It is originally an access / path. When we re-point it to '/home', it is equivalent to accessing '/home'. Correspondingly, the home component will be displayed on the page. Redirect is used in vueRouter to define redirects.
const routes = [ { path:"/home", component: home }, { path: "/about", component: about }, // Redirect { path: '/', redirect: '/home' } ]
Now the page is normal. You can enter the home for the first time and click to see the content toggle.
6. Finally, let’s take a look at how the routing is implemented
When you open the browser console, you first see that the router-link tag is rendered into a tag, and the to attribute becomes the href attribute of the a tag. At this time, you understand the meaning of clicking to jump. The router-view tag is rendered into the component we define. In fact, it is a placeholder. Wherever it is, the component matching the path is located. Therefore, the router-link and router-view tags correspond one by one and appear in pairs.
It is also seen here that when clicking Home and About to switch back and forth, the a tag has a style class .router-link-active, which is also switching back and forth. It turns out that this is when router-link is in the selected state, vueRouter will automatically add this class, so we can also use this class to change the selected state, such as when selected, make it turn red. But when setting .router-link-active {color: red;}, it does not take effect. At this time, you should add a, -link-active {color: red;} to the class, so there is no problem. The router-link that is not selected, we also want to change the style of it. What should we do? Just add a class to it directly, <router-link class="red">Home</router-link>
Dynamic routing
The routes we defined above are strictly matched. Only when the to attribute in router-link is exactly the same as the path in a route in js, the corresponding component can be displayed. But sometimes the reality is not like this. When we visit the website and log in successfully, it will display Welcome, + your name. Different users log in, just display the "Your Name" part different, the other parts are the same. This means that it is a component, assuming it is a user component. Different users (that is, the user's ids are different), they will navigate to the same user component. In this way, when we configure the route, we cannot write it dead. That is, the path attribute in the route cannot be written dead. How should we set it? Navigate to the user component, and there must be user and ids in the path, so give the path a dynamic part to match different ids. In vue-router, the dynamic part starts with :, and the path becomes /user/:id. This route can be written like this: { path:"/user/:id", component: user }.
We define a user component (just write one by yourself), add two router-links to the page for navigation, and finally add the routing configuration to experience it
Add two router-links:
<template> <div > <img src="./assets/"> <header> <router-link to="/home">Home</router-link> <router-link to="/about">About</router-link> <!-- Add two touserComponent navigation,You can see that different use is used heretoproperty --> <router-link to="/user/123">User123</router-link> <router-link to="/user/456">User456</router-link> </header> <router-view></router-view> </div> </template>
Configure user dynamic routing:
const routes = [ { path:"/home", component: home }, { path: "/about", component: about }, /*Added user path, configured with dynamic id*/ { path: "/user/:id", component: user }, { path: '/', redirect: '/home' } ]
user component
<template> <div> <h1>User</h1> <div>I amuserComponents</div> </div> </template> <script> export default { } </script>
At this time, click user123 and user456 on the page, and you can see that they are both navigated to the user component and configured correctly.
In dynamic routing, how to get the dynamic part? Because different parts can be displayed in the component, that is, the "your name" mentioned above. In fact, after the entire vue-router is injected into the root instance, the router instance can be obtained through this.$route inside the component. It has a params property, which is to get this dynamic part. It is an object, the attribute name is the dynamic part defined in the path id, and the attribute value is the dynamic part of the to attribute in the router-link, such as 123. When using vuex, if you want to get the state in the state in the component, you use the computed attribute. The same is true here. In the component, define a computed attribute dynamicSegment. The user component is modified as follows:
<template> <div> <h1>User</h1> <div>I amuserComponents, The dynamic part is{{dynamicSegment}}</div> </div> </template> <script> export default { computed: { dynamicSegment () { return this.$ } } } </script>
There is another last problem here, that is, when dynamic routes switch back and forth, since they all point to the same component, vue will not destroy and create this component, but reuse this component. That is, when the first click (such as user123), vue renders the corresponding component, but when user123 and user456 click to switch back and forth, this component will not change, and the component's life cycle will no longer work. At this time, if you want to do something when the component is switched back and forth, you can only use watch inside the component (in) to listen for changes in $route. Implement the above code with listening $route
<script> export default { data () { return { dynamicSegment: '' } }, watch: { $route (to,from){ // to represents the component you are going to, from represents which component you came from, they are two objects, you can print it out, and they also have a param property (to); (from); = } } } </script>
Nested routing
Nested routing is mainly determined by our page structure. When we enter the home page, there are categories below, such as mobile phone series, tablet series, and computer series. When we click on each category, it still needs to route to each part. For example, if you click on the phone, it will definitely reach the corresponding part to the phone.
In the routing design, you first enter home, and then you can enter phone, tablet, computer. Phone, tablet, compute is equivalent to entering the child element of home. So vue provides childrens attribute, which is also a set of routes, equivalent to the routes we write.
First, define three router-link tags on the home page for navigation, and then define a router-view tag to render the corresponding components. The router-link and router-view tags must correspond one by one. The components are modified as follows:
<template> <div> <h1>home</h1> <!-- router-link oftoAttributes should be paid attention to,The route is to enter firsthome,然后才进入相应of子路由如 phone,So when writing home Bring it with you --> <p> <router-link to="/home/phone">cell phone</router-link> <router-link to="/home/tablet">flat</router-link> <router-link to="/home/computer">computer</router-link> </p> <router-view></router-view> </div> </template>
Configure routing, modify it as follows:
const routes = [ { path:"/home", //The following attributes are also quite a few, because we first enter the home page to enter the sub-router. component: home, // Subroutine children: [ { path: "phone", component: phone }, { path: "tablet", component: tablet }, { path: "computer", component: computer } ] }, { path: "/about", component: about }, { path: "/user/:id", component: user }, { path: '/', redirect: '/home' } ]
At this time, when we click home, the words "mobile phone" appear below it, but no corresponding components are displayed, which is usually not what we want. To click on the home, to render the corresponding subcomponents, you also need to configure a route. When entering home, its corresponding route path in children is empty ‘', and the complete children are as follows:
children: [ { path: "phone", component: phone }, { path: "tablet", component: tablet }, { path: "computer", component: computer }, // When entering home, the following components are displayed { path: "", component: phone } ]
Named routes
Naming a route is very simple, because you can know based on the name that this route has a name, so just add a name attribute to the route. Add a name attribute to the user route:
{ path: "/user/:id", name: "user", component: user }
To use named routes, you can use objects by the to attribute in router-link.
<router-link to="/user/123">User123</router-link> // is equivalent to the following <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> // When using objects as routes,toAdd a colon before it,Indicates binding
Programming navigation: This is mainly applied to button clicks. When clicking the button, jump to another component, which can only be used with code and call
()
method. After injecting the router into the root instance, the router can be obtained through this.$router in the component, so it is used in the componentthis.$("home"),
You can jump to the home interfaceSummarize
The above is the basic use of vue router introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!