• This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

VueRouter_ basis

What is routing?

Routing displays different content or pages based on different URLS. In the early days, the back end reloaded the page according to the URL directly, that is, the back end controlled the route. Later the page is more and more complex, the server pressure is more and more, with the advent of Ajax (asynchronous refresh technology), the realization of the page can refresh data without overload, so that the front end can also control url self-management, front-end routing from this.

When to use front-end routing?

Front-end routing is more used in single-page applications, namely SPA(Single Page Web Application). In single-page applications, the results of most pages remain unchanged, but only the use of part of the content is changed.

Install the routing

NPM install vue-router.

Use the routing

JavaScript

  1. The introduction of the routing
import VueRouter from 'vue-router';
Copy the code
  1. Use the routing
Vue.use(VueRouter);
Copy the code
  1. Defining routing Components
 // You can import from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
Copy the code
  1. Define the routing
 // Each route should map one component
const routes = [
  { path: '/foo'.component: Foo },
  { path: '/bar'.component: Bar }
]
Copy the code
  1. Create a Router instance and then pass itroutesconfiguration
const router = new VueRouter({
  routes 
})
Copy the code
  1. Create and mount the root instance
const app = new Vue({
  router
}).$mount('#app')
Copy the code

html

<div id="app">
  <h1>Hello App!</h1>
  <p>
     <! -- Use the router-link component to navigate. 
     <! -- Specifies the link by passing in the 'to' attribute. 
     <! -- <router-link> will be rendered as a '<a>' tag by default. 
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
   <! -- Route exit --> 
   <! -- Routing matching components will be rendered here --> 
  <router-view></router-view>
</div>
Copy the code

router-link class

  • Router-link-exact-active Displays a path that matches the value of the component’s to property
  • Router-link-active The current display path contains the value of the to attribute

To change the class name

VueRouter({
  linkActiveClass: 'link-active'.linkExactActiveClass: 'link-exact-active',})Copy the code

The last

If it is helpful to you, I hope to give you a 👍 comment/collection/three even!

Bloggers are honest and answer questions for free ❤