Atmega8, atmega16, the smallest system board, the first praise is here!

2022-12-28   ES  

ajaxtechnology, when the front and back end are not separated, often when we access a URL through the browser, the back end will return the full page of the corresponding URL(html+css+js), that is, the page we see is like this at the back end.
So when there are dozens of hundreds of pages on a website, the requests for these URLs (paths) need to be organized and managed to return the specified webpage for the specified request path. This is the back -end route.

and appearajaxAfter technology, the front and back end quickly separated and emerged with SPA (single page rich application). The back -end is mainly responsible for providing interfaces. The front end is mainly responsible for page rendering. The page we see is generated at the front end.
The main process is this, passed by the front endajaxRequest interface, the back end returns the corresponding data, after getting the data in the front end, and then run some of the corresponding templatesjsto generatedom, so the presentation of the page becomes a front -end thing, and the front determines which page to display which page. Similarly, when the page gradually becomes more, we also need to manage it, which becomes the front -end route

WhenSPA, you will directly request all the front -end files, and then presented according to the routing selective rendering.
Therefore, when visiting other routing, the webpage will not be refreshed because all front -end files(html+css+js)In the first time, I have requested it.The exception of requests using AJAX to interact with the back end), the front end will monitor the changes in the routing, and switch the display of the page

So how do you do the routing change and the browser is not refreshed?

// Method 1: Change local
location.hash = 'foo'
// Method two: Change the History object
// Push into the record of the top of the stack
history.pushState({
    }, '', 'home')
// or
// Replace the top record of the stack
history.replaceState({
    }, '', 'home')

在这里插入图片描述
These two methods will not refresh the browser (the page is not reloaded)

// Other methods to expand the history
history.back() 	// back a page back
// equivalent to
history.go(-1)

history.forward() // Go forward a page
// equivalent to
history.go(1)

npm install --save vue-router
	// The current version used
    "vue": "^2.5.2",
    "vue-router": "^3.0.1"

According to the habits of use, establish the following file structure

/src
	/router
		-index.js

在这里插入图片描述
and then configure the routing related information in the index.js

import VueRouter from 'vue-router'
import Vue from 'vue'

Vue.use(VueRouter)

export default new VueRouter({
    
    // Configure the mapping relationship between routing and components
    routes: [

    ]
})

Then guide in main.js

import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
    
  el: '#app',
  router,
  render: h => h(App)
})
  • In order to map the relationship, we first create two components, the structure is as follows
/src
	/components
		/about
			-About.vue
		/home
			-Home.vue

在这里插入图片描述
The content is as follows

<!-- Home.vue -->
<template>
  <div>
      <h1>I am home</h1>
  </div>
</template>
<script>
export default {
     
  name: 'Home',
}
</script>
<!-- About.vue -->
<template>
  <div>
      <h1>I am About</h1>
  </div>
</template>
<script>
export default {
     
  name: 'About',
}
</script>
  • Configuration mapping rules:
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/home/Home.vue'
import About from '../components/about/about.vue'

Vue.use(VueRouter)

export default new VueRouter({
    
    // Configure the mapping relationship between routing and components
    routes: [
        {
    
            path: '/home',
            component: Home
        },
        {
    
            path: '/about',
            component: About
        }
    ]
})

app.vue content is as follows

<template>
  <div id="app">
    <router-link to="/home">home</router-link>
    <!--
	<router-link :to="{path: '/home'}">home</router-link>
	-->
    <router-link to="/about">about</router-link>
    <router-view></router-view>
  </div>
</template>

<script>

export default {
     
  name: 'App',
}
</script>

Here you can see two new tags in the app.vue. These two labels are registered by Vue-Router global. So we can use these two tags anywhere in the template
Router-link is used to jump to the routing, switch to display different components
ROUTER-VIEW is used to occupy a place, indicating where the corresponding component of the routing should be displayed

<!-- 
  Router-Link's tag property 
  Router-Link tags are converted into A tags by default. When needed to be converted into other tags, you can specify in the tag attribute 
 ->
<router-link to="/home" tag="button">Homepage</router-link>

<!-- 
  Router-Link's replace property 
  Router-Link labels the History.pushState () defaults to the default use, which means that the routing record can be returned. 
  If you don't want to save the previous routing record, you can specify the replace attribute 
 ->
<router-link to="/home"  replace>Homepage</router-link>

<!-- 
  Router-Link's class attribute 
  When router-link label corresponds to the routing matching successfully, it will automatically set a Router-Link-Active class 
  You can also modify the name of this class. For example, modify it to Active 
 ->
<router-link to="/home" active-class="active">Homepage</router-link>
  • Configuration redirection
// router/index.js part of the content
    routes: [
    	{
    
    		// When the user accesses the root routing, it will redirect to '/Home', and then display the home component
    		path: '/',
    		redirect: '/home'
    	},
        {
    
            path: '/home',
            component: Home
        },
        {
    
            path: '/about',
            component: About
        }
    ]
  • Configuration routing mode
    As mentioned earlier, there are two ways to change the route without refreshing the webpage. One is the other is HISTORY. Therefore, the routing mode is also divided into these two.
// router/index.js part of the content
export default new VueRouter({
    
	// Set the routing mode as the history (this feeling is better)
    mode: 'history',
    routes: [
		...
    ]
})
  • Configure Router-Link activation style
// router/index.js part of the content
export default new VueRouter({
    
	// Global modification, unlike local modifications that add Active-Class attributes to Router-Link
	// Usually not to modify this category name
	linkActiveClass: 'acitve',
    routes: [
		...
    ]
})
  • Configuration dynamic route
    routes: [
        {
    
        	// userid is dynamic, and can be obtained through route.params.userid
            path: '/user/:userId',
            component: User
        }
    ]
  • Configuration embedded route
        {
    
            path: '/home',
            component: Home,
            children: [
            	// The effect of the two writing methods is the same
                {
    
                	// plus / indicating the starting of the root routing
                    path: '/home/news',
                    component: HomeNews
                },
                {
    
                	// without / indicate the start of the parent route
                    path: 'message',
                    component: HomeMessage
                }
            ]
        },

  • Change the route through code

methods: {
    
	homeClick() {
    
		// Reserve route records
		this.$router.push('/home')
		// or not retained routing records
		this.$router.replace('/home')
	}
}
  • Get Params parameters
// When the dynamic routing is configured, you can get the params parameter in the current ROUTE object
// Note that route is not router
// router is an object exposed in /router/index.js, which can be accessed on all routing pages
// Route is the object of the routing page, so the params that obtain a specific page should be taken on the ruote
<template>
  <div>
      <h1>User {
    {
    user}}</h1>
  </div>
</template>

<script>

export default {
    
  name: 'About',
  computed: {
    
      user() {
    
          return this.$route.params.userId
      }
  }
}
</script>

  • Get Query parameter
<!-- App.vue -->
<template>
  <div id="app">
  	<!-Pass the Query parameter->
    <router-link to="/home?name=dd&age=18">home</router-link>
    <!--
    <router-link :to="{path: '/home', query: {name:'dd', age: 18}}">home</router-link>
	-->
    <router-link to="/about">about</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
     
  name: 'App',
}
</script>
<!-- Home.vue -->
<template>
  <div>
    <h1>I am home</h1>
    <router-link to="/home/news">News</router-link>
    <router-link to="/home/message">Message</router-link>
    <!-Use through route->
    <div>{
   {$route.query.name}}</div>
    <div>{
   {$route.query.age}}</div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
     
  name: 'Home',
}
</script>

  • Demand: If all resources are packaged in a JS, then the request to visit the webpage for the first time will be very slow.

  • Playing a good directory structure
    在这里插入图片描述
    can see Vue-CLI’s webpack configuration, which is to divide the packed files (by default, just one entrance and one exit, all resources are packaged in bundle.js)

    // js file prefix explanation
    app:Refers to the code written by the programmer's own 
     manifest:The underlying support code, such as __webpack_require__ function used when modular 
     vendor:refers to third -party code, such as Vue

    From the above analysis, it can be obtained. The amount of code of Manifest and VENDOR is basically fixed, and it is impossible to partial requests. The app will increase dynamic growth with the increase in business logic. At the same time APP is made into blocks.

  • Use routing lazy loading

// router/index.js
import VueRouter from 'vue-router'
import Vue from 'vue'

// The important thing is the writing of needed on demand
const Home = () => import('../components/home/Home.vue')
// AMD style introduction
// const Home = resolve => require(['../components/home/Home.vue'], resolve)
const About = () => import('../components/about/About.vue')
const User = () => import('../components/user/User.vue')

Vue.use(VueRouter)

export default new VueRouter({
    
    mode: 'history',
    routes: [
        {
    
            path: '/',
            redirect: '/home'
        },
        {
    
            path: '/home',
            component: Home
        },
        {
    
            path: '/about',
            component: About
        },
        {
    
            path: '/user/:userId',
            component: User
        }

    ]
})

Look at the directory structure after packing
在这里插入图片描述
Three routes imported on demand, corresponding to the three new JS files (.map is the corresponding auxiliary file)
Everyone may have any questions. Isn’t the app being separated? Why is there still existing apps, because the parts are divided into routes, and some components such as app.Vue are to be loaded at the beginning, not loaded on demand on demand. Therefore, the app is not completely separated

Demand: You need to do some intermediate operations when the route jumps

// router/index.js part of code
const router =  new VueRouter({
    
    mode: 'history',
    routes: [
    	{
    
			path: '/home',
			component: Home,
			// You can store some data in Meta so that
			meta: {
    
				name: 'dd',
				age: 18
			}
		}
		...
    ]
})
// Pre -hook (HOOK)
router.beforeEach((to, from, next)=>{
    
    // to: Objective Route
    // from: source route
    // Next: Promoting the routing function, you must call it, otherwise the routing jump will fail

    // Do some logic between jumping

    next()

})

// Rear hook
// Because it is called after the routing switch is completed), no need to call next ()
router.afterEach((to, from)=>{
    
    // ...
})

export default router

In addition, there are routing exclusive guards

// router/index.js part of code
const router =  new VueRouter({
    
    mode: 'history',
    routes: [
    	{
    
			path: '/home',
			component: Home,
			meta: {
    
				name: 'dd',
				age: 18
			},
			beforeEnter: (to, from, next) => {
    
				// ...
				next()
			}
		}
		...
    ]
})

Demand: It will be destroyed when the routing component is switched. After the switching is returned, it will be re -created. This leads to the loss of operation on this routing component. At this time, I hope to save the state of this routing component.

<!-Keep-alive label outside the Router-View label. At this time, the routing component displayed in it will not be destroyed by switching->
<keep-alive>
	<router-view/>
</keep-alive>

Sometimes, we want to destroy a certain component when switching, but he is nested in the Keep-Alive label, and you can use the EXCLUDE attribute to eliminate

<keep-alive>
	<!-Home, user is the name of the component. In the .vue file, specified by the name attribute->
	<router-view exclude="Home,User"/>
</keep-alive>

Similar, and the INCLUDE attribute, the effect is the opposite

source

Related Posts

Samba service configuration

SpringBoot uses RESTTEMPLATE to send Post request postforentity (Application/X-WWW-Form-Urlencoded)

Use paddleDetection to convert its homemade Labelme dataset to COCO format

PAT Class A 1070 MoonCake

Atmega8, atmega16, the smallest system board, the first praise is here!

Random Posts

python’s threading module

In GitHub’s public source code, causing millions of losses, DJI programmers have been sentenced to 6 months, and those who fined 200,000 programs

[Unity & C# & Interface] The component of the interface of different types of objects was called through the interface

Mock.js Commonly used placeholders -BASIC, Date, Color

Spring Boot+Bootstrap implements dynamic rotation map actual combat