current position:Home>Routing: Vue router
Routing: Vue router
2022-04-29 07:21:19【Reluctantly】
What is routing ?
Routing is the activity of transmitting information from the source address to the destination address through the Internet .
The development stage of web pages
Back end routing phase :
Handled by the backend URL Mapping between and pages , The pages displayed at the front end are processed at the back end .
Front and back separation stage :
With Ajax The emergence of Technology , With the development mode of front end and back end separation , The backend is only responsible for providing data , Not responsible for the content of any stage . Most of the content in the web page displayed in the browser , It's all written by the front end js The code is executed in the browser , The final rendered web page , Front end rendering .
Single page rich application stage :
SPA(Single page application) A layer of front-end routing is added on the basis of front-end and back-end separation , The front end maintains a set of routing rules . There's only one page html page , Front end pair url Mapping between and pages .
What is? vue-router?
vue-router yes Vue.js The official routing plug-in , And vue.js Deep integration , Suitable for building single page applications . Routing is used to set the access path , Mapping paths and components , stay vue-router In a single page application , The change of page path is the switching of components .
vue-router Encapsulation
Step one : install vue-router plug-in unit
npm install vue-router --save
Step two : Used in modular engineering
- Import routing objects , And call Vue.use( VueRouter )
- Create a routing instance , And incoming route mapping configuration
- stay Vue The created routing instance is mounted in the instance
vue-router Use
install vue-router after , stay src New under the directory router Folder , And create index.js File :
(Vue CLI Select when creating a project vue-router The directory file can be automatically generated after )
router/index.js
// Configure routing information
import Router from 'vue-router'// Import vue-router
import Vue from 'vue'// Import vue
import HelloWorld from '@/components/HelloWorld'
//Vue.use( plug-in unit ), Installing a plug-in
Vue.use(Router)
// Create and export
export default new Router({
routes: [// Handle url Mapping relationship between and components
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
stay main.js Import and reference... In the file
main.js
import Vue from 'vue'
import App from './App'
import router from './router'// Import created router
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
})
Configure the mapping relationship of routes :
stay components Create two components under the folder : Home.vue、About.vue file
<template>
<div>
<h2>Home</h2>
<p>Home Components </p>
</div>
</template>
<script>
export default {
name:"Home"
}
</script>
<style>
</style>
<template>
<div>
<h2>About</h2>
<p>About Components </p>
</div>
</template>
<script>
export default {
name:"About"
}
</script>
<style>
</style>
Configure mapping relationships : open router/index.js file , To configure routers:[]
// Configure routing information
import Router from 'vue-router'// Import vue-router
import Vue from 'vue'// Import vue
// Import the created component Home、About
import Home from '../components/Home'
import About from '../components/About'
//Vue.use( plug-in unit ), Installing a plug-in
Vue.use(Router)
// Create and export
export default new Router({
routes: [// Handle url Mapping relationship between and components
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
}
]
})
stay App.vue Write labels in the file to switch routes :
<template>
<div id="app">
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
Fixed label <router-link></router-link> and <router-view></router-view>
router-link and router-view yes vue Two components of automatic registration , The former will eventually be rendered as a label , The latter determines where the rendered components are displayed , You can't have one without the other .
Running results :
Summarize the above vue-router How to use :
- Create routing component
- Configure route mapping : Mapping relationship between components and routes
- Using routing : adopt <router-link> and <router-view>
Default configuration for routing :router/index.js
// Create and export
export default new Router({
routes: [// Handle url Mapping relationship between and components
{// Set the default path of the route
path:'',
redirect:'/home',// Redirect , Once the page path is ' ' when , The default point to /home
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
}
],
mode:'history',// By default hash The way : #/home, It is amended as follows history After the model , by : /home
// linkActiveClass: 'active' // Add... When the route tag is clicked class The attribute is active, By default router-link-exact-active
})
Project operation , The default point is /home
<router-link> Properties of
<router-link> except to Property to perform route jump , There are other attributes , such as tag attribute
By default ,<router-link> It will be rendered as <a> label :
<router-link to="/home" tag="button">Home</router-link>
<router-link to="/about" tag="button">About</router-link>
replace attribute : You can't use the... In the upper left corner of the browser Do the return operation :
<router-link to="/home" tag="button" replace>Home</router-link>
When the route jump tab is clicked ,vue A... Will be automatically added to the tag class:
Through this property , We can control the click style of the label .
App.vue Add styles to :
<style>
.router-link-exact-active{
color: red;
}
</style>
Route code jump
<template>
<div id="app">
<!-- <router-link to="/home" tag="button">Home</router-link>
<router-link to="/about" tag="button">About</router-link> -->
<button @click="homeClick">Home</button>
<button @click="aboutClick">About</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
homeClick(){
// Modify the route through the code : vue-router Added... For each element $router attribute
this.$router.push('/home')// Implement route modification , Can return
// this.$router.replace('/home')// Can't return
},
aboutClick(){
this.$router.push('/about')// Implement route modification
// this.$router.replace('/about')// Can't return
}
}
}
</script>
<style>
.router-link-exact-active{
color: red;
}
</style>
Dynamic routing
Sometimes a page path The path is likely to be uncertain , For example, when we enter the user interface , The following path is expected :
/user/aaa,/user/bbb,/user/ccc, Except for the front /user outside , It also keeps up with the user's ID. such path and componment The matching relationship is dynamic routing , It's also a way of routing data .
New component User.vue
<template>
<div>
<h2> The user interface </h2>
<p> Dynamic routing </p>
</div>
</template>
<script>
export default {
name: 'User',
}
</script>
<style>
</style>
Configure the routing :router/index.js
// Configure routing information
import Router from 'vue-router'// Import vue-router
import Vue from 'vue'// Import vue
// Import the created component Home、About
import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'
//Vue.use( plug-in unit ), Installing a plug-in
Vue.use(Router)
// Create and export
export default new Router({
routes: [// Handle url Mapping relationship between and components
{// Set the default path of the route
path:'',
redirect:'/home',// Redirect , Once the page path is ' ' when , The default point to /home
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:userId',
component: User
}
],
mode:'history',// By default hash The way : #/home, It is amended as follows history After the model , by : /home
// linkActiveClass: 'active' // Add... When the route tag is clicked class The attribute is active, By default router-link-exact-active
})
App.vue
<template>
<div id="app">
<router-link to= "/home" tag="button">Home</router-link>
<router-link to= "/about" tag="button">About</router-link>
<router-link :to= "'/user/'+ userId" tag="button"> user </router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userId:'xiaoyuer'
}
}
}
</script>
<style>
.router-link-exact-active{
color: red;
}
</style>
Running results :
this.$route Get the currently active route ( Clicked ),this.$router For the entire routing object , Including many routes .
this.$route.params You can get some parameter information of the current active route , for example :
User.vue
<template>
<div id="app">
<router-link to= "/home" tag="button">Home</router-link>
<router-link to= "/about" tag="button">About</router-link>
<router-link :to= "'/user/'+ userId" tag="button"> user </router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userId:'xiaoyuer'
}
}
}
</script>
<style>
.router-link-exact-active{
color: red;
}
</style>
Running results :
Road load by lazy :
When we package an application ,javaScript The bag will get very big , Affects page loading . If we can divide the components corresponding to different routes into different code blocks , Then, when the route is accessed, the corresponding components are loaded , This can be more efficient .
ES6 Lazy loading in writing :
const Home = () => import('../components/Home.vue')
router/index.js
// Configure routing information
import Router from 'vue-router'// Import vue-router
import Vue from 'vue'// Import vue
// Import the created component Home、About
// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'
// Lazy loading way
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
//Vue.use( plug-in unit ), Installing a plug-in
Vue.use(Router)
// Create and export
export default new Router({
routes: [// Handle url Mapping relationship between and components
{// Set the default path of the route
path:'',
redirect:'/home',// Redirect , Once the page path is ' ' when , The default point to /home
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:userId',
component: User
}
],
mode:'history',// By default hash The way : #/home, It is amended as follows history After the model , by : /home
// linkActiveClass: 'active' // Add... When the route tag is clicked class The attribute is active, By default router-link-exact-active
})
So when packing , Each component will be packaged into a separate js file . When the page needs to be loaded , Then call the corresponding components , Improve application performance .
copyright notice
author[Reluctantly],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290427564035.html
The sidebar is recommended
- With the blessing of tinnove system, Changan uni-v does not have its own table
- Judging the application direction of small flat wire motor from SM 4x4 driverless technology verification vehicle
- Vue3 + nuxt3 build SSR website application, and realize server-side rendering from 0 to 1 without secret Fen sharing
- Vue3 + nuxt3 build SSR website application, and realize server-side rendering from 0 to 1 without secret Fen sharing
- Vue3 + nuxt3 build SSR website application, and realize server-side rendering from 0 to 1 without secret Fen sharing
- React bread crumbs
- HTTP network protocol
- Vue3 + nuxt3 build SSR website application, and realize server-side rendering from 0 to 1 without secret Fen sharing
- Vue3 + nuxt3 build SSR website application, and realize server-side rendering from 0 to 1 without secret Fen sharing
- Use of vuex
guess what you like
Element UI El table modify input value view not updated
Getsnapshotbeforeupdate example of react
Recently, the MySQL server on the cloud was hacked. It took 20 minutes to modify the password after being mercilessly encrypted. This time I'll be hacked with your last name
Java project: sporting goods Mall (java + springboot + jsp + HTML + Maven + MySQL)
Java project: shared study room reservation management system (java + springboot + thymeleaf + HTML + Maven + MySQL)
Java project: sporting goods Mall (java + springboot + jsp + HTML + Maven + MySQL)
Java project: shared study room reservation management system (java + springboot + thymeleaf + HTML + Maven + MySQL)
Sennheiser momentum true wireless 3 true wireless headphones will be available on May 10
How to realize Ethernet wireless communication between 200smartplc?
Coffeescript 2.7.0 release, JavaScript translation language
Random recommended
- Still working on nginx configuration? Try this visual configuration tool. It's really powerful!
- Im instant messaging development: load balancing of high-performance HTTP server
- Simple sorting of JavaScript deep copy and shallow copy
- React realizes the communication of brother components by means of message subscription and publication
- React limits props
- Java lesson 30
- Java lesson 29 136 The number 1189 appears only once Maximum number of balloons
- Simple sorting of JavaScript deep copy and shallow copy
- "Geely" new SUV is equipped with frameless doors, and the interior is more beautiful than Mercedes Benz. Can 19 universal accept it?
- Configuration of using less in react project
- Expression used in react render
- React configuration agent
- JQuery sends a post request (a method of connecting PHP variables to strings)
- Solve the problem that Django cannot access the local server( http://127.0.0.1:8000/ )Or the problem that the command line execution (Python 3 manage.py runserver 0.0.0.0:8000) does not respond
- Summary of the writing method of react router V6
- Bipeng ditch, punch in and net red, open-air boundless swimming pool, Ramada hot spring, encounter the beauty of the four seasons
- JavaScript gets and modifies elements. What's wrong with not extracting the classlist attribute
- Mixed mixin of Vue
- Vue + element implements table filtering
- Vue router2. 0
- Which one charges less for opening a securities account and how to open the account
- Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download
- Httpclient setting timeout
- Command line / Python uses pdf2htmlex to convert PDF to HTML
- [front end three swordsmen III] analysis of JavaScript scalpel Part II
- How to choose the front-end learning path
- Finite element parametric element, calculation, theoretical problems
- Handwritten CSS modules to understand its principle
- Front end browser debugging tips
- Performance problem analysis guide for enterprise JavaScript applications running in production systems
- CSS aspect-ratio All In One
- Actual combat of vue3 project --- Zhihu daily --- details page
- Actual combat of vue3 project --- Zhihu daily --- home page function
- Great Wall Motors is falling endlessly! The boss has lost 150 billion yuan in half a year, and the performance of the new energy sector has improved
- Nginx tips batch shutdown process
- Openresty introduces nginx_ upstream_ check_ Module module
- Nginx multiple servers_ How does name match
- Why does the front end still prompt cannot post, and the error reported by the back end still prompt null pointer?
- HTML Li set margin: 50%, but the width of the outermost div is the standard
- Are there any specific steps to create a prototype, such as JavaScript?