[Spring Boot + Vue]: front-end routing VueRouter

1. Basic concept of VueRouter

Vue-Router is the official routing plugin for Vue.js, making it easy to build single-page applications with Vue.js. Features include:

  • Nested route-maps
  • dynamic routing
  • Modular, component-based routing configuration
  • Route parameters, queries, wildcards
  • Demonstrates transition effects provided by Vue.js’ transition system
  • Detailed Navigation Controls
  • Links to auto-activate CSS classes
  • HTML5 history mode or hash mode
  • Customizable scrolling behavior
  • Correct Encoding of URLs

Vue is more suitable for single-page projects, and the content of all web pages is switched through an Html page. In this Html page, different routes are used to control the display of different components. This control requires Vue-Router to complete.

Vue’s single-page application is based on routing and components. Routing is used to set the access path and map (correspond to) the path and components. Accessing different paths will display different components.

Typical single page usage

All content is displayed on one Html page, and each title is a component. After clicking, the content is switched in different components to display different content.

Vue-Router currently has two versions. Version 3.X and Version 4.X

Vue-Router3.X version can only be used in conjunction with Vue2;
Vue-Router4.X version can only be used in conjunction with Vue3;

Vue-Router installation

Vue-Router3.X version: npm install vue-router@3

Vue-Router4.X version: npm install vue-router@4

Official documentation:
https://router.vuejs.org/zh/

If using it in a modular project, the routing function must be explicitly installed via Vue.use():

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue. use(VueRouter)

2. Example demonstration:

  • Create a new project (this example uses Vue2), see the previous note (9) for the specific installation process

    Drag the newly created project vuerouter-demo into Visual Studio Code. Currently there is no Vue-Router in the project that needs to be installed.

Note: In this example, Vue2 is used, so vue-router3 needs to be installed

Enter the following command in the terminal in Visual Studio Code:

npm install vue-router@3

After the installation is complete, you can see vue-router3 in package.json

  • Create a routing component:

The following simulates the interface of Netease Music, customizes the three components Discover.vue, Friends.vue, and My.vue in the project components folder, and uses Vue-Router to control their display and switching.

Discover.vue:

<template>
 <div>
 <h1>Discover music</h1>
 </div>
</template>

Friends.vue

<template>
 <div>
 <h1>Follow</h1>
 </div>
</template>

My.vue

<template>
 <div>
 <h1>My Music</h1>
 </div>
</template>

All three components need link correspondence, which needs to be described by Vue-Router.

  • Declare routing links and site tags

You can use tags to declare route links, and use tags to declare route stoppers.

We perform routing jumps in the root component App.vue, the code is as follows:

 <!--declare routing link-->
 <router-link to="/discover">Discover music</router-link>
 <router-link to="/friends">Follow</router-link>
 <router-link to="/my">My Music</router-link>


At this time, there are three buttons on the App component. If you are interested, you can use CSS to beautify the style. At this time, click but cannot jump yet. Because the corresponding relationship between the defined link and the three components has not been set. Because the corresponding relationship is more complicated, it can be written in a separate js file.

  • Create a routing module

Create a router folder in the project src, create a new routing module named index.js in it, and define the corresponding relationship in it, the code is as follows:

//Import Vue and VueRouter
import VueRouter from "vue-router";
import Vue from "vue";
//import component
import Discover from '../components/Discover.vue'
import Friends from '../components/Friends.vue'
import My from '../components/My.vue'
//Set VueRouter as a plugin for vue
Vue. use(VueRouter)

const router = new VueRouter({<!-- -->
 //Specify the correspondence between the hash attribute and the component
 routes:[
 {<!-- -->path:'/discover',component:Discover},
 {<!-- -->path:'/friends',component:Friends},
 {<!-- -->path:'/my',component:My},
 ]
})


path corresponds to the link; comment corresponds to the component.

At this point, where should the component be displayed? This requires a station label. Put the components where they need to be displayed. Let’s put it in the root component App.vue as an example, the code is as follows:


Once the user clicks “discover music”, the browser will jump to discover . According to the definition of the previous route, discover corresponds to the Discover component. At this time, the content of the Discover component will be rendered to this position, thereby completing the jump switching of the interface.

Next, you need to export the route in index.js, the code is as follows:

export default router


Finally, import and set it in main.js, the code is as follows:

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

Vue.config.productionTip = false

new Vue({<!-- -->
 render: h => h(App),
 router:router
}).$mount('#app')


Run npm run serve to start the project.

The first loading is to the home page. If the component is loaded at this time but no content is displayed, this is not appropriate. A default loaded component will be specified in the actual project. For example, in NetEase Cloud Music, the default is to enter the “discover music” component when entering the home page.

  • 3.vue-router advanced

route redirection
When the user visits address A, the user is forced to jump to address B, so as to display the page of a specific component.

By specifying a new routing address through the redirect attribute of the routing rule, it is very convenient to set the routing redirection.

For example, redefining the home page to display the “discover music” component

{<!-- -->path:'/',redirect:"/discover"},

  • Nested routing

Components can be nested under components, for example, sub-routes such as “Recommendation” and “Song List” can be nested under “Discover Music”.

In the Discover.vue component, declare the sub-routing links and sub-routing placeholders of toplist and playlist, the code is as follows:

<template>
 <div>
 <h1>Discover music</h1>
 <!--Sub-routing link-->
 <router-link to="/discover/toplist">Recommended</router-link>
 <router-link to="/discover/playlist">Playlist</router-link>
 
 <router-view></router-view>
 </div>
</template>


At this time, two components, Toplist and Playlist, need to be created.

Then introduce the Toplist and Playlist components in index.js, and set the corresponding relationship by nesting and declaring sub-routes through the children attribute. At this time, the complete code of index.js is as follows:

//Import Vue and VueRouter
import VueRouter from "vue-router";
import Vue from "vue";
//import component
import Discover from '../components/Discover.vue'
import Friends from '../components/Friends.vue'
import My from '../components/My.vue'
import Toplist from '../components/Toplist.vue'
import Playlist from '../components/Playlist.vue'
//Set VueRouter as a plugin for vue
Vue. use(VueRouter)

const router = new VueRouter({
 //Specify the correspondence between the hash attribute and the component
 routes:[
 //When the user visits /, switch to /discover
 {<!-- -->path:'/',redirect:"/discover"},
 {path:'/discover',
 component:Discover,
 //Through the children attribute, sub-routes can be nested and declared
 children:[
 {path:"toplist",component:Toplist},
 {path:"playlist",component:Playlist},
 ]
 },
 {path:'/friends',component:Friends},
 {path:'/my',component:My},
 ]
})

//export the default route
export default router


  • Dynamic Routing

Many routing links, as follows:

<router-link to="product/1">Product 1</router-link>
<router-link to="product/2">Product 2</router-link>
<router-link to="product/3">product 3</router-link>
const router = new VueRouter({<!-- -->
 //Specify the correspondence between the hash attribute and the component
 routes:[
 {<!-- -->path:"prodect/1",component:Prodect},
 {<!-- -->path:"prodect/2",component:Prodect},
{<!-- -->path:"prodect/3",component:Prodect},
 ]
 },
 {<!-- -->path:'/friends',component:Friends},
 {<!-- -->path:'/my',component:My},
 ]
})

The reusability of the above method is very poor.

Thinking: If there is a product list, when the user clicks on the product, it will jump to the product details. Each product will have product details. It is impossible to write a product detail component for each product. At this time, I hope to reuse the content in the component when jumping to the detail component.

Dynamic routing: It is to define the variable part of the Hash address as a parameter item, so as to improve the reusability of routing rules. Use English colons ( : ) in vue-router to define routing parameter items, as follows:

{<!-- -->path : '/prodect/:id,component:Prodect'}

The following is an example demonstration:

1. If you have a product, you need to build a product component first: Product.vue

2. Assuming that the product component is a sub-route based on the My.vue component, modify the My.vue component as follows:

<template>
 <div>
 <h1>My Music</h1>
 <router-link to="/My/1">Product 1</router-link>
 <router-link to="/My/2">Product 2</router-link>
 <router-link to="/My/3">Product 3</router-link>
 <router-view></router-view>
 </div>
</template>

3. Set the corresponding relationship in index.js, first import the Prodect.vue component

import Prodect from '../components/Prodect.vue'

4. Use the children attribute to define the jump, the code is as follows:

{<!-- -->path:'/my',
 component: My,
 children:[
 {<!-- -->path:":id",component:Prodect},
 ]
 },

5. Start the project, and the effect can be displayed in the browser: click “My Music”, and then click any one of the displayed products 1/2/3, and the content of “product” can be displayed.

Now there is a problem, when jumping to the Product.vue component, how do you know how many details of the product need to be displayed?

Workaround:

Method 1: In the component rendered by dynamic route matching, you can use the $route.params object to access the dynamically matched parameter items. For example, inside the product details component, request different product data according to the id value. Modify the code as follows:

At this time, click on a different product to display the details of the product

Method 2: In order to simplify the acquisition of routing parameters, vue-router allows props to be passed in routing rules. Modify the sample code in index.js as follows:

{<!-- -->path:":id",component:Prodect,props:true},

The Prodect.vue component is modified as follows: first define a parameter id; then $route.params is not needed, and can be directly used to pass parameters by id, and the browser display effect is the same as above.

<template>
 <h3>Item {<!-- -->{<!-- --> id }}</h3>
</template>

<script>
export default {<!-- -->
 props:["id"]
}
</script>
  • Programmatic navigation (this is only for understanding, and will be demonstrated in detail later in the comprehensive application)

Declarative navigation:

Programmatic navigation: router.push(…)

In addition to using the a tag to define the navigation link, you can also use the instance method of router to implement it by writing code.

To navigate to a different URL, use the router.push method. This method will add a new record to the history stack. So, when the user clicks the browser’s “Back” button, it returns to the previous URL.

This method is called internally when is clicked. So, clicking is equivalent to calling router.push(…) .

<template>
 <div>
 <h3>Recommended</h3>
 <button @click="gotoProduct(2)">Jump to product 2</button>
 </div>
</template>

<script>
export default {<!-- -->
 methods: {<!-- -->
 gotoProduct:function(id){<!-- -->
 this.$router.push('/movie/${<!-- -->id}')
 }
 }
}
</script>
  • navigation guard

Navigation guards can control access to routes

For example, if you want to jump to the order page without logging in, you can use the routing guard for unified control.

The global navigation guard intercepts each routing rule to control access to each route. You can use router.beforeEach to register a global beforeEach guard:

router.beforeEach(( to,from,next )=>{<!-- -->
 if ( to.path === '/main' & amp; & amp; !isAuthenticated){<!-- -->
 next('/login')
 }
 else{<!-- -->
 next()
 }
})

o: about to enter the target

from: the route that the current navigation is leaving

In the guard method, if the next parameter is declared, the next() function must be called, otherwise the user is not allowed to access any route

Direct release: next()

Force to stay on the current page: next(false)

Force jump to the login page: next( ‘/login’ )