4. Vue – the Router

Routing is the activity of transferring information from a source address to a destination address over an interconnected network

1.1. Back-end routing and front-end routing

  • Back-end rendering/back-end routing
  • Front end separation
  • SPA/ front-end routing

Back-end rendering: The server directly produces and renders the corresponding HTML pages and returns them to the client for display. For example: JSP pages

Front-end rendering: most of the content of the web page displayed in the browser is executed by the FRONT-END JS code in the browser, and the final rendering of the web page. (The back end returns JSON data, and the front end uses a pre-written HTML template to loop through the JSON data, concatenate strings, and insert pages.)

Back-end routing: When the browser switches between different urls in the address bar, each time it sends a request to the backend server, the server responds to the request, the server renders the entire page, and returns the page to the client.

Front-end routing: Core – Changes URL, but does not refresh the page as a whole.

1.2. The SPA page

SPA: Single page rich application, the entire web page has only one HTML page.

The most important feature of SPA is to add a layer of front-end routing on the basis of the separation of front and back ends.

The core of front-end routing is to change the URL, but not refresh the page as a whole.

1.3. The URL hash

The HASH of the URL, also known as the anchor point (#), essentially changes the href attribute of window.location.

We can change the href by assigning location.hash directly, but the page does not refresh.

Location. href "http://192.168.1.101:80/" location.hash = '/foo' "http://192.168.1.101:80/#/foo"Copy the code

1.4. HTML5 history mode

  • pushState
  • back
  • forward
  • replaceState
  • go
History. PushState ({}, ' ', '/ foo) location. The href "http://192.168.1.101:80/foo" is history. ReplaceState ({},' ', '/ foo') Location. The href "http://192.168.1.101:80/foo" "http://192.168.1.101:80/foo" is history. Go. (1) the location href "Http://192.168.1.101:80/" is history. The go (1) "http://192.168.1.101:80/foo"Copy the code

1.5. The Vue Router

Vue-router is based on routes and components

  • Routing is used to set access paths and map paths to components.
  • In a vue-Router single-page application, a change in the path of the page is a component switch.

1.6. Install and Use routes

Step 1: Import the route object and call vue.use (VueRouter) step 2: Create the route instance and pass in the route mapping configuration Step 3: import the route object and call vue.use (VueRouter) Import Vue from 'Vue' import VueRouter from 'vue-router' const Home = () => import('.. /components/Home.vue') const About = () => import('.. /components/About.vue') const Message = () => import('.. /components/Message.vue') const news = () => import('.. /components/news.vue') vue. use(VueRouter) The steps to use vue-router are as follows: Step 1: Create routing components step 2: Configure routing mapping: Component and path mapping Step 3: Use routing: <router-link> and <router-view> // define const routers = [{path: '/', redirect: '/home'}, {path: '/home', Component: Children: [{path: 'message', Component: message,}, {path: 'news', Component: news,}, {path: 'news', // Children: [{path: 'message', Component: message,}, {path: 'news', component: news,} '', redirect: 'message' } ] }, { path: '/about', component: }] // Create router instances const router = new VueRouter({routers, // Use HTML5 history mode for routers: 'history' // Change the default class name of the active-class attribute (router-link-active) LinkActiveClass: New vue ({el: '#app', router, render: H => h(APP)}) <router-link>: this tag is a component already built into vue-Router and will be rendered as a <a> tag. <router-view>: This tag will dynamically render different components based on the current path. The rest of the page, such as the title/navigation at the top, or some copyright information at the bottom, is at the same level as the <router-view>. During route switching, the components mounted by <router-view> are switched, and other contents remain unchanged.Copy the code

1.7. Other router-link attributes

  • To:, property: to, used to specify the jump path.
  • Tag: Tag can specify which component will be rendered later. For example, the code above will be rendered as one
  • Element, rather than
  • Replace: Replace does not leave a history, so if you specify replace, the back key will not return to the previous page
  • Active-class: When the route matches successfully, the system automatically sets a router-link-active class for the current element. If you set LinkActiveClass, you can change the default name.
    • This class is used when performing highlighted navigation menus or tabbars at the bottom.
    • The default router-link-active is used instead of modifying the class attributes.

1.8. Page route redirects

<button @click="linkToHome">Home page</button>

<script>
	export default {
        name: 'App'.methods: {
          linkToHome() {
              this.$router.push('/home')}}}</script>
Copy the code

1.9. Dynamic Routing

1.91. Types of Params
  • Set the route format to /router/: ID
  • How it is passed: Follow path with the corresponding value
  • The path is /router/123, /router/ ABC
{path: '/user/:userId', Component: User} < the router - link to = "/ User / 123" > User < / router - the link > < div > < h3 > {{$route. Params. UserId}} < / h3 > < / div > {{this.$route.params.userId}}Copy the code
1.92. Type of 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
{{$route.params}} {{$route.query}}Copy the code
1.93. Two ways of passing parameters

Parameter transfer mode 1:


The second way to pass parameters: JavaScript code

1.94.
r o u t e and The route and
A router is different
  • Router is an instance of VueRouter. If you want to navigate to different urls, you use router as instance VueRouter. If you want to navigate to different urls, you use router.push

  • $route indicates the current router jump object, which can obtain name, path, query, and params

2.0. Lazy loading of routes

Function: Package the component corresponding to the route into a js code block, only when the route is accessed, load the corresponding component.

A: Const Home = resolve => {require.ensure(['../components/ home.vue '], () => { resolve(require('.. /components/Home.vue')) })}; Const About => require(['../components/ about.vue '], resolve); Const Home = () => import('.. /components/Home.vue')Copy the code

2.1. Nested routine by

2.2. Navigation Guard

website

  • Vue-router provides a navigational guard that listens for incoming and outgoing routes.
  • Vue-router provides beforeEach and afterEach hook functions that fire before and after a route is about to change.
We can define some headers in the hooks and use the meta to define them. We can also modify our headers using the navigation guard. '/home', Component: home, meta: {title: 'home'}}, {path: '/about', Component: about, title: 'about'}] const router = new VueRouter({routers,}) Router. BeforeEach ((to, from, next) => { window.document.title = to.meta.title; Next ()}) export default Router Navigation hook three parameters: to: destination route object to enter from: current navigation route object to leave next: call this method to enter the next hook.Copy the code

2.3 keep alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

  • Two attributes:
    1. Include-string or regular expression. Only matching components are cached
    2. Exclude – a string or regular expression. Any matching component will not be cached

Router-view is also a component. If it is wrapped directly in keep-alive, all view components matched by the path will be cached.

Verify this by declaring a periodic function by create.

2.4. TabBar case

  1. If you had a separate TabBar component underneath, how would you encapsulate it

    • Custom TabBar components for use in the APP
    • Put TabBar at the bottom and set the styles
  2. What is displayed in TabBar is determined by the outside world

    • Define the slot
    • Flex layout bisects the TabBar
  3. Custom TabBarItem that can pass in images and text

    • Define TabBarItem and define two slots: picture and text.
    • Wrap divs around the two slots to set styles.
    • Fill the slots to achieve the bottom TabBar effect
  4. Pass in the highlight image

    • Define another slot to insert active-icon data
    • Define a variable isActive, using v-show to determine whether to display the corresponding icon
  5. TabBarItem Binds routing data

    • Install route: NPM install vue-router -save
    • Complete the contents of router/index.js and create the corresponding component
    • Register the router in main.js
    • Add components to your APP
  6. Click item to jump to the corresponding route and dynamically determine isActive

    • Listen for item clicks and replace the routing path with this.$router.replace()
    • Through this $route. Path. IndexOf (enclosing the link). == -1 To check whether it is active
  7. Compute the active style dynamically

    • Encapsulate new compute properties: this.isactive? {‘color’: ‘red’} : {}

Code implementation