current position:Home>Routing: Vue router

Routing: Vue router

2022-04-29 07:21:19Reluctantly

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

  1. Import routing objects , And call Vue.use( VueRouter )
  2. Create a routing instance , And incoming route mapping configuration
  3. 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 :

  1. Create routing component
  2. Configure route mapping : Mapping relationship between components and routes
  3. 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

Random recommended