Vue learning – Routing Router

Know the routing

What is front-end rendering and what is back-end rendering?

Back-end rendering phase

Back-end rendering: JSP-Java Server Page

After the background receives the request, HTML + CSS + Java, Java code function is to read the data from the database, and dynamically put it on the page, the page has been rendered on the server side, and then directly render the good page back to the front end (HTML + CSS)

Back-end routing: The backend handles the mapping between urls and pages

Disadvantages of back-end routing:

  • Modules for the entire page are written and maintained by back-end staff
  • If front-end developers develop pages, they need to write page code through PHP, Java and other languages
  • All too often, HTML code gets mixed up with data and logic, and writing and maintaining it can be very messy

Front and rear end separation stage

Input jd.com, first go to static resource browser to request static resources (HTML + CSS + JS), when the browser engine executes JS code, will trigger API request, will go to the background API server to request data.

Front-end rendering: most of the content of the web page displayed in the browser is written by the front-end JS code, executed in the browser, and finally rendered out of the web page.

  • With the advent of Ajax, the development model of front – and back-end separation was replaced
  • The back end only provides apis to return the data, while the front end gets the data through Ajax and can render the data to the page through JS
  • The biggest advantage of this approach is the clarity of responsibility on the front and back ends, with the back end focused on data and the front end focused on interaction and visualization
  • And when the mobile end appears, the back end does not need to do any processing, still use the previous set of apis

Front-end routing stage (single-page rich application stage)

On the basis of front – end separation, plus front-end routing

SPA application: The whole site has only one HTML page, one SET of HTML + CSS + JS

Front-end routing: The front-end manages the mapping between the page and static resources. The whole page is not refreshed when the URL is changed

Url hash and HTML5 history

In the URL hash

  • The hash in the URL, also known as the anchor point (#), essentially changes the href attribute of window.location
  • You can change the href by assigning location.hash directly, but the page does not refresh
  • location.hash = 'aaa'

The history of it

  • history.pushState({}, '', 'home')Push the
  • history.replaceState({}, '', 'home')replace
  • Replace cannot return to the previous page, and push can return to the previous page
  • history.go()Parameter: -1:history.back() 1: history.forward()

Vue-router is used basically

Install the vue – the router

npm install vue-router --save
Copy the code

Use vue-router in modular projects (plugins that use vue.use () to use routing)

  • Import the routing object and call vue.use (VueRouter)
  • Create a route instance and pass in the route mapping configuration
  • The created routing instance is mounted to the Vue instance

Frame structures,

import Vue from 'vue'
// Import the routing object and call vue.use (VueRouter)
import VueRouter from 'vue-router'
import Home from '.. /views/Home.vue'

Vue.use(VueRouter)

// Create a route instance and pass in the route mapping configuration
const routes = [
    {
        path: '/'.name: 'Home'.component: Home
    },
    {
        path: '/about'.name: 'About'.// route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () = > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}]const router = new VueRouter({
    mode: 'history'.base: process.env.BASE_URL,
    routes
})

// First exit, then mount the created routing instance in the Vue instance in main.js
export default router

Copy the code

Configure the routing

  • Creating a Routing Component
  • Configuring route mapping: Component and path mapping
  • Using routing: Pass and
{
    path: '/'.name: 'Home'.component: Home
},
    {
        path: '/about'.name: 'About'.// route level code-splitting
                // this generates a separate chunk (about.[hash].js) for this route
                // which is lazy-loaded when the route is visited.
                // Route lazy loading
                component: () = > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}Copy the code
<router-link to="/home">Home page</router-link>
<router-link to="/about">about</router-link>
<router-view></router-view>
Copy the code

Change the route default value and to history mode

Default route value

{ path: '/', redirect: 'home' }
Copy the code

The history mode

mode: history

const router = new VueRouter({
    mode: 'history'.base: process.env.BASE_URL,
    routes
})
Copy the code

Other attributes of router-link

The tag attributes

Render as a tag by default. To render as other elements, use the tag attribute

<router-link to="/home" tag="button">Home page</router-link>
<router-link to="/about" tag="button">about</router-link>
Copy the code

The replace property

By default, pushState is used, and if you want to use replaceState, replace is used

</router-link> <router-link to="/about" tag="button" </router-link to="/about" tag="button" The replace > about < / router - the link >Copy the code

.router-link-active

The selected router-link automatically has the. Router-link-active class, which can be directly used to set the style, for example, the selected font becomes red

.router-link-active {
	color: red;
}
Copy the code

. Router-link-active short mode

<router-link to="/home" tag="button" replace active-class="acive"> </router-link> <router-link to="/about" tag="button" Replace active-class="acive"> About </router-link>Copy the code
.active {
	color: red;
}
Copy the code

Modify active-class in a unified manner

const router = new VueRouter({
    mode: 'history'.base: process.env.BASE_URL,
    routes,
    linkActiveClass: 'active'
})
Copy the code

Jump routes by code

this.$router.push('/home');
Copy the code
this.$router.replace('/home')
Copy the code

Dynamic routing

<router-link to="/home">Home page</router-link>
<router-link to="/about">about</router-link>
<router-link to="/user/zhangsan">The user</router-link>
<router-link :to="'/user/' + userId">The user</router-link>
Copy the code
{ path: '/user/:userId'.component: User }
Copy the code

or

this.$router.push('/user/' + this.userId)
Copy the code

The userId is obtained in user. vue

{{$route.params.userId}} or this.$route.params.userId // $route: active route // $router: entire route objectCopy the code

Lazy loading of routes

  • Javascript packages can become very large when packaged to build applications, affecting page loads

  • If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the routes are accessed, this will be more efficient than (one route packaged with a JS file).

  • Lazy loading: Load only when needed

// The recommended way
const routes = [
	{ path: '/home'.component: () = > import('.. /components/Home')}, {path: '/about'.component: () = > import('.. /components/About')}]Copy the code

or

const About = resolve= > require(['.. /components/About.vue'], resolve);
Copy the code

Vue-router Indicates the nested routine

Learn about route nesting

  • For example, in the home page, we want to access some content through /home/news and /home/message
  • A path maps a component, and accessing these two paths also renders two components separately

Steps to create nested routines

  • Create the corresponding child components and configure the corresponding child routes in the routing map
  • Use labels inside components
{ path:  '/home'.component: Home, children: [{path: 'news'.component: HomeNews },
    { path: 'message'.component: HomeMessage },
    { path: '/'.redirect: 'news'}}]Copy the code
<router-link to="/home/news">news</router-link>
<router-link to="/home/message">The message</router-link>
Copy the code

Vue-router parameter transfer

Jump from one page to another, hoping to deliver some message

Method 1: The method described in dynamic routing can pass parameters

  • Set the route format to /router/: ID
  • How it is passed: Follow path with the corresponding value
  • The paths are /route/123 and /route/ ABC

Method 2: Query

  • The route format is /router, which is the common configuration
  • Pass method: The object uses the Query key as the pass method
  • Route: /router? id=123 , /router? id=abc
<router-link :to={path: '/profile', query: {name: 'xx', age: 18, height: 1.88}}"></router-link>
Copy the code

or

this.$router.push({
	path: '/profile'.query: {
        name: 'xx'.age: 18.height: 1.88}})Copy the code
{{$route.query.name}} or this.$route.query.nameCopy the code

Vue-router: Indicates the origin of router and route

All components (.vue) inherit the vue prototype, which in turn mounts RouterG and RouterG and RouterG and Route

Vue.prototype.$router = { ... } Vue.prototype.$route = { ... } orObject.defineProperty(Vue.prototype, '$router',...). ;Object.defineProperty(Vue.prototype, '$route',...). ;Copy the code

This.$Router is an instance of the vueRouter class

This.$route is the active route

Vue-router Navigation guard

Requirements:

How do I change the title of a web page in a SPA application?

  • Page titles are passed<title>But SPA has only one fixed HTML, and the title does not change when switching between pages
  • This can be modified via Javascript<title>The content of theWindow.document. title=" New title"
  • So in the VUE project, how to achieve?

Solution 1: The lifecycle function is created

Scenario 2: Use global navigation guard (front hook, front guard)

router.beforeEach((to, from, next) = > {
	// Jump from from to to
	document.title = to.matched[0].meta.title;
    next();
})
Copy the code
{ path: '/home'.component: Home, meta: { title: 'home'}}Copy the code

Rear hook:

AfterEach has already jumped

router.afterEach((to, from) => {
	
})
Copy the code

Route exclusive guard

const router = new VueRouter({
	routes: [{
        path: '/foo'.component: Foo,
        beforeEnter: (to, from, next) = >{}}]})Copy the code

keep-alive

  • Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering
  • Router-view is also a component. If it is wrapped directly in keep-alive, all view components that match the path will be cached
<keep-alive>
    <router-view></router-view>
</keep-alive>
Copy the code
  • The activated() and deactivated() hook functions only work if they are wrapped by keep-alive

  • If you want one of your components to be created and destroyed frequently

    Don’t put a space after the Profile User comma

    <keep-alive exclude="Profile,User">
        <router-view></router-view>
    </keep-alive>
    Copy the code

Path alias

You can use @ instead of SRC in VUE-cli3

case

App.vue

<template> <div id="app"> <router-view></router-view> <tab-bar> <tab-bar-item path="/home" activeColor="red"> <img SVG "Alt ="" slot="item-icon"> <img SRC ="./assets/image/tabbar/ home _active.svg" Alt ="" Slot ="item-icon-active"> <div slot="item-text"> home </div> </tab-bar-item> <tab-bar-item path="/category" ActiveColor =" SkyBlue "> <img SRC ="./assets/image/tabbar/ categoric. SVG "Alt ="" slot="item-icon"> <img SRC ="./assets/image/tabbar/ class_active. SVG "Alt ="" slot="item-icon-active"> <div slot="item-text"> <tab-bar-item path="/cart" activeColor="green"> <img SRC ="./assets/image/tabbar/ shopping cart SRC ="./assets/image/tabbar/ shopping cart _active-svg "Alt ="" slot="item-icon-active"> <div slot="item-text"> shopping cart </div> </tab-bar-item> <tab-bar-item path="/profile"> <img SRC ="./assets/image/tabbar/ my. SVG "Alt ="" slot="item-icon"> <img SRC ="./assets/image/tabbar/ my _active. SVG "Alt ="" slot="item-icon-active"> <div slot="item-text"> My </div> </tab-bar-item>  </tab-bar> </div> </template> <script> import TabBar from "./components/tabbar/TabBar"; import TabBarItem from "./components/tabbar/TabBarItem"; export default { name: 'App', components: { TabBar, TabBarItem } } </script> <style lang="css"> @import './assets/css/base.css'; </style>Copy the code

TabBar.vue

<! -- --> <template> <div id="tab-bar"> <slot></slot> </div> </template> <script> export default { name: 'TabBar', data () { return { }; } } </script> <style lang='css' scoped> #tab-bar { display: flex; background-color: #f6f6f6; position: fixed; left: 0; right: 0; bottom: 0; /* Shadow */ box-shadow: 0px -1px 1px rgba(100, 100, 100, 0.2); } </style>Copy the code

TabBarItem.vue

<! -- --> <template> <div class="tab-bar-item" @click="itemClick"> <div v-if="! isActive"><slot name="item-icon"></slot></div> <div v-else><slot name="item-icon-active"></slot></div> <div :style="activeStyle"> <slot name="item-text"></slot> </div> </div> </template> <script> export default { name: 'TabBarItem', props: { path: String, activeColor: { type: String, default: 'red' } }, data() { return { }; }, methods: { itemClick() { this.$router.push(this.path).catch(err => {}); } }, computed: { isActive() { return this.$route.path.indexOf(this.path) ! = = 1; }, activeStyle() { return this.isActive ? { color: this.activeColor } : {}; }}}; </script> <style lang='css' scoped> .tab-bar-item { flex: 1; text-align: center; height: 49px; font-size: 14px; } .tab-bar-item img { width: 24px; height: 24px; margin-top: 3px; vertical-align: middle; } </style>Copy the code

rendering