catalogue
Front end Routing & & back end routing
Complete navigation guard analysis process
Front end Routing & & back end routing
The functions of routing include routing (mapping) and forwarding
Back end routing
Back end rendering: it is equivalent to passing the url address to the server, and the server will render the web page according to HTML+css + back-end language, and then return to the front end. The content includes HTML+css, of course, HTML containing data.
Steps for back-end Routing:
1: A page has a corresponding url, that is, a url
2: The url is sent to the server for matching and handed over to a controller for processing
3: After various processing, the controller returns html data to the front end
4: Complete an i/o operation
Front end routing
Front end rendering: most of the content displayed on the web page in the browser is rendered by js in the browser. When inputting some specific url addresses, it will first go to the static resource server to request the corresponding html+css+js code and download it, and then obtain the data at the server providing the API interface, and finally render it after being converted by front-end ajax.
SPA page (single page rich application): the main feature of SPA is to add a layer of front-end routing on the basis of front-end and back-end separation, and the whole web page has only one html page. In SPA, the static resource server contains only one html file, or even a set of html+css+js files. When the url changes, the corresponding relevant code will be found in js first, separated and then rendered on the client.
vue develops a typical single page application by default. There is only one html page in the public folder.
Front end Routing: handle the mapping relationship between url and page at the front end.
The core of front-end routing is to change the url without overall page refresh, and use js instead of requesting from the server.
How to change the url without page refresh?
1. hash of URL
The hash of the URL, that is, the anchor, essentially changes the href attribute of window.location.
We can change the href by directly assigning location.hash, but the page does not refresh.
2. history of HTML5
history.pushState({},'','home')
history.pushState is equivalent to the operation of stack, first in, last out, bouncing stack and entering stack.
history.pushState stack;
history.back() out of the stack;
history.go(-1) Equivalent to history.back();
history.forward is equivalent to history.go(1);
history.replaceState(): cannot return;
--------
Copyright notice: This article is the original article of CSDN blogger "Nezha", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/guorui_java/article/details/120626879
vue-router
Get started
<html> <head> <meta charset="utf-8"> <title></title> <script src="./vue.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <p> <router-link to="/foo">go to foo</router-link> <router-link to="/bar">go to bar</router-link> </p> <router-view></router-view> </div> <script type="text/javascript"> //Define routing components var Foo = {template:'<div>foo</div>'}; var Bar = {template:'<div>bar</div>'}; //Define route const routes = [ {path:'/foo' , component:Foo}, {path:'/bar' , component:Bar}, ] //Create a router instance and transfer the routes configuration const router = new VueRouter({ routes:routes }) //Create a root instance and mount the div const app = new Vue({ router }).$mount("#app") </script> </body> </html>
Here, a simple route is implemented, including the following steps:
1 define two routing components, of which there are only templates
2. Configure the routing object and create the mapping relationship between the path and the component
3. Create router instance and pass in configuration
4. Create a root instance and mount the route
Two basic tags are used in html: router link and router view
router-link:
Tag: tag can specify what components the router link will render, such as < router link tag ='button '> < / router link >, which is a button at this time;
Replace: adding the replace attribute is equivalent to replaceState;
class: you can add a style to the label. For example, the selected one will be automatically assigned router link active;
Active class = "active": selected; Linkactiveclass can also be configured in router component: 'active';
--------
Copyright notice: This article is the original article of CSDN blogger "Nezha", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/guorui_java/article/details/120626879
router-view:
The area displayed according to the components of the route map
Component development of Routing:
In component-based development, Vue router is uniformly managed in router.js, and AMD specification is used to introduce components
import downApp from '@/components/downApp.vue'
Then reference the Router and expose the interface. Generally, this step is already done when building a project using webpack
Vue.use(Router) export default new Router({ //History mode, that is to filter out useless information in front of the linked home page on the page mode:'history', routers:[{}...] })
The parameters are path (path), name (optional, route name), alias (optional, alias), component (component name), meta (optional, metadata, mostly used for navigation guards), redirect (optional, redirection, mostly used for navigation guards to return to the original page)
The component-based development of index.js is roughly divided into five steps:
1. import component
2. use (Router) because it is a plug-in, the routing function can be installed through Vue.use()
3. Create a routing configuration object
4. Create a routing instance and pass in the routing configuration
5,export default router
All components of component-based development are basically placed in views
Component development finally imports the route in main.js and imports it when creating the root instance
Nested Route
With the help of Vue router, using nested routing configuration, can simply express this relationship.
Next, the app created in the previous section:
<div id="app"> <router-view></router-view> </div>
const User = { template: '<div>User {{ $route.params.id }}</div>' } const router = new VueRouter({ routes: [{ path: '/user/:id', component: User }] })
there < router-view> It is the top-level exit, rendering the components matched by the highest-level route. Similarly, a rendered component can also contain its own nesting < router-view>. For example, in User Add a template for the component < router-view>:
const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` }
To render components in nested exits, you need to VueRouter Used in parameters of children to configure:
const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ { // When / user/:id/profile matches successfully, // The UserProfile will be rendered in the User's < router View > path: 'profile', component: UserProfile }, { // When / user/:id/posts match successfully // UserPosts will be rendered in the User's < router View > path: 'posts', component: UserPosts } ] } ] })
Be careful to / The first nested path is treated as the root path. This allows you to make full use of nested components without setting nested paths.
You'll find, children Configuration is like routes Configure the same route configuration array, so you can nest multiple routes.
At this point, based on the above configuration, when you access / user/foo User The exit will not render anything because there is no matching to the appropriate sub route. If you want to render something, you can provide an empty sub route:
const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ // When / user/:id matches successfully, // UserHome will be rendered in User's < router View > { path: '', component: UserHome } // ... other sub routes ] } ] })
Transfer from official documents
Lazy loading of routes
When packaging and building applications, JavaScript packages become very large, affecting page loading.
If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed, it will be more efficient.
Lazy loading method:
(1) Code analysis combining Vue asynchronous component and Webpack
const Home = resolve => { require.ensure(['../components/Home.vue'],
() => { resolve(require('../components/Home.vue')) })};
(2) amd writing method
const About = resolve => require(['../components/About.vue'], resolve);
(3) In ES6, we can have a simpler way to organize the code segmentation of Vue asynchronous components and Webpack
const Home = () => import('../components/Home.vue')
demo:
// import Home from '../components/Home' // import About from '../components/About' // import User from '../components/User' // Lazy loading mode const Home = () => import('../components/Home') const About = () => import('../components/About') -------- Copyright notice: This article is CSDN Blogger「nezha」Original articles, follow CC 4.0 BY-SA Copyright agreement, please attach the original source link and this statement. Original link: https://blog.csdn.net/guorui_java/article/details/120626879
Navigation guard
Complete navigation guard analysis process
- Navigation is triggered.
- Called in an inactive component beforeRouteLeave Guard.
- Call Global beforeEach Guard.
- Called in a reused component beforeRouteUpdate Guard (2.2 +).
- Called in routing configuration beforeEnter.
- Resolve asynchronous routing components.
- Called in the activated component beforeRouteEnter.
- Call Global beforeResolve Guard (2.5 +).
- Navigation confirmed.
- Call Global afterEach Hook.
- Trigger DOM update.
- call beforeRouteEnter Pass it to the guard next The created component instance will be passed in as a parameter of the callback function.
Global guard
router.beforeEach((to, from, next) => { console.log(to) => // To which page? console.log(from) => // From which page? next() => // A callback function } router.afterEach(to,from) = {}
Each guard method receives three parameters:
-
to: Route: the target to enter Routing object
-
from: Route: the route that the current navigation is about to leave
-
next: Function: be sure to call this method to resolve This hook. Execution effect dependence next Method.
-
next(): the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed (confirmed).
-
next(false): interrupt the current navigation. If the URL of the browser is changed (either manually by the user or the browser Back button), the URL address will be reset to from The address corresponding to the route.
-
next('/') perhaps Next ({path: '/'}): jump to a different address. The current navigation is interrupted and a new navigation is performed. You can ask next Pass an object anywhere and allow settings such as replace: true,name: 'home' And anything used in router-link of to prop or router.push Options in.
-
next(error): (2.4.0 +) if passed in next The parameter is a Error Instance, the navigation will be terminated and the error will be passed to router.onError() Registered callback.
-
ensure next The function is strictly called once in any given navigation guard. It can occur more than once, but only when all logical paths do not overlap, otherwise the hook will never be parsed or reported an error.
Route exclusive guard
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
The parameters are the same as the global guard
Component local guard
const Foo = { template: `...`, beforeRouteEnter(to, from, next) { // Before rendering the component, the corresponding route is called before confirm. // no Yes! Get component instance ` this` // Because the component instance has not been created before the guard is executed }, beforeRouteUpdate(to, from, next) { // Called when the current route changes but the component is reused // For example, for a path / foo/:id with dynamic parameters, when jumping between / foo/1 and / foo/2, // Since the same Foo component will be rendered, component instances will be reused. The hook will be called in this case. // Can access component instance ` this` }, beforeRouteLeave(to, from, next) { // Called when the navigation leaves the corresponding route of the component // Can access component instance ` this` } }
beforeRouteEnter guard No visit this, because the guard is called before the navigation confirmation, the new component to be launched has not been created.
However, you can pass a callback to next to access the component instance. The callback is executed when the navigation is confirmed, and the component instance is used as the parameter of the callback method.
An instance of a guard:
This demo is used to verify whether a user is currently logged in. If not, it will forcibly jump to the login interface
router.beforeEach((to,from,next)=>{ let user=window.localStorage.getItem("user");//Read whether there is login information let token=window.localStorage.getItem("token"); if(user!=null&&token!=null && to.path == '/login'){//If you have logged in and the jump path is login, it is not allowed next('/home') } else if(to.path == '/login' || to.path == '/register'){//If there is no login, the jump path is login, then release next(); }else if(user===null&&token===null){//If the path to go is not login and there is no login, forcibly jump to the login window alert('You haven't logged in yet. Please log in first'); next('/login'); } else next(); })