Vue Router:
- Vue Router (Part 1)
- Vue Router Dynamic Parameter Transfer and Navigation Guard
Dynamic routing
In normal projects, in addition to the standard routing output described in the previous chapter, more often we use dynamic routing and JavaScript code to control the jump to the page.
The method of controlling through JavaScript code was demonstrated at the end of the previous chapter, and we’ll use the example in the previous section to demonstrate this.
Old rule, green flower on the code:
- The component that introduces dynamic routes to router/index.js is displayed after path
:id
{
path: "/about/:id".name: "About".// This component is lazily loaded. This is recommended
component: () = >
import(/* webpackChunkName: "about" */ ".. /views/About.vue")}Copy the code
- Modify the code in app.vue as follows
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="'/about' + id">About</router-link>
</div>
<router-view/>
</div>
</template>
<script>
export default {
data:function(){
return {
id: 123}},</script>
Copy the code
Then we can see that the ID in the route will automatically match the ID value passed in the component data. This is the basic use of dynamic routing. If you want to dynamically obtain the ID value in the route, there are two ways:
- through
$route.params.id
Direct access to - Get with a calculated property!
<script>
export default {
data:function(){
return {
id: 123
},
computed: {Id(){
$route = $route = $route
return this.$route.params.id
}
}
},
</script>
Copy the code
Dynamic routes transmit parameters in JS mode
First, let’s talk about the application scenario of this method of parameter passing. Generally, get request is used when searching, filtering, sorting and other operations are carried out on the website. Then, the URL of get request will pass parameters to the URL to achieve this function, as shown below:
https://www.baidu.com/s?wd=vue
Copy the code
Wd =vue after the question mark is the url type parameter!
- Universal knowledge, URL composition:
A URL can consist of seven parts: the protocol part (HTTP/HTTPS), the domain part (www.baidu.com), the port part (:8000), the virtual directory part (/news/), and the file part (starting with the last ‘/’ after the domain name and ending with ‘? Up), the anchor part (starting with “#” and ending), the parameter part (starting with “?” Start until “#”).
Specific you can understand by yourself!
- Such get requests are typically constructed in vUE by,
path
collocationquery
(similar to get), can pass$route.query
Get the parameters passed!
Old rule, green flower on the code:
<! --App.vue-->
<h1>Code to jump</h1>
<button @click="ProfileClick">Profile</button>
<script>
export default {
methods: {
ProfileClick(){
this.$router.push({
path: '/profile'.query: {
name: 'vue'.age: 18.height: 10}},}</script>
Copy the code
Click ProfileClick event will jump to as http://www.xxx.com/profile?name=vue&age=18&height=10 in the form of address!
- The typical way to construct a POST request in vUE is by,
name
collocationparams
(Similar to POST)
The usage scenario is that when we send data to the POST interface, we can use this method to pass parameters to the interface!
Old rule, green flower on the code:
<! --App.vue-->
<h1>Code to jump</h1>
<button @click="UserClick">Profile</button>
<script>
export default {
methods: {
ProfileClick(){
this.$router.push({
name: 'user'.query: {
id: 12.name: 'vue'.desc: 'learning vue'}},}</script>
Copy the code
In this way, you can push data to the POST request interface, passing parameters that can be obtained via $route.params!
Embedded routines by
If a large route has a small branch route under it, it is consistent with the principle of route creation. A route corresponds to a component, and child routes must also correspond to related components one by one. Then, the registered route is imported to the component of the parent route through the
.
Same old rule. Get the code on the flower!
// router/index.js
// Create page components in the views folder in advance.
const Home = () = > import('.. /views/Home.vue')
const HomeNews = () = > import('.. /views/HomeNews')
const HomeMessage = () = > import('.. /views/HomeMessage')
const routes = [
{
path: '/'.name: 'home'.component: Home,
/ / child component
children: [
// Jump links
{
path: '/'.redirect: '/home/news'
},
{
// the path is the same as that referenced to the component
path: '/home/news'.component: HomeNews
},
{
path: '/home/message'.component: HomeMessage
}
]
},
]
Copy the code
Imports a child route into a component of the parent route.
<router-link to="/home/news">news</router-link> |
<router-link to="/home/message">message</router-link>
</router-view>
Copy the code
Navigation guard
The navigational guard means that it listens to the progress of each route, and then provides hooks that give you the opportunity to embed information in the progress of the route. The navigational guard is divided into three parts: global navigational guard, route navigational guard and component guard.
Global navigation guard
Global navigation guard is divided into the following three categories, I suggest you go to the vUE official website about this, have a basic understanding!
1. Global front Guard:
router.beforeEach
To call back when a route jumps!
router.beforeEach((to, from, next) = > {
// If the user fails to authenticate, 'next' will be called to the login page
if(to.name ! = ='Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
Copy the code
2. Global parse guard
Router.beforeresolve This is similar to router.beforeeach, except that the parse guard is called before the navigation is confirmed and after all the guard and asynchronous routing components are parsed.
3. Global post-hook
router.afterEach
Jump back!
Route exclusive guard
You can define beforeEnter guards directly on the routing configuration:
const router = new VueRouter({
routes: [{path: '/foo'.component: Foo,
beforeEnter: (to, from, next) = > {
// ...}}}])Copy the code
These guards have the same method parameters as the global front-guard.
Component internal guard
Finally, you can define the following route navigators directly within the routing component:
- beforeRouteEnter
beforeRouteEnter (to, from, next) {},
Copy the code
Called before the corresponding route to render the component is confirmed, no! Can!!!! Gets component instance this because the component instance has not been created before the guard executes. However, you can access the component instance by passing a callback to Next. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method.
beforeRouteEnter (to, from, next) {
next(vm= > {
// Access component instances through 'VM'})}Copy the code
For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing callbacks are not supported because they are not necessary.
- BeforeRouteUpdate (2.2 New)
Called when the current route changes but the component is being reused. For example, for a path with dynamic parameters,/foo/:id, jumping between /foo/1 and /foo/2 will render the same foo component, so the component instance will be reused. And the hook will be called in that case. You can access the component instance this!
beforeRouteUpdate (to, from, next) {
// just use `this`
this.name = to.params.name
next()
}
Copy the code
- beforeRouteLeave
Called when navigating away from the component’s corresponding route, accessing the component instance this. This departure guard is usually used to prevent users from abruptly leaving without saving changes. This navigation can be cancelled by next(false).
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes! ')
if (answer) {
next()
} else {
next(false)}}Copy the code
Add the following information to router/index.js:
// router/index.js
// 01. Add meta object metadata to the navigation route
{
path: '/home/message'.name: 'message'.component: HomeMessage,
meta: {
title: 'message'}}// 02. Add the following methods
// Global navigation guard, router is an object that we initially new
// Global navigation guard [front hook, jump callback]
router.beforeEach((to, from, next) = > {
// Jump from from to to
document.title = to.matched[0].meta.title
console.log('+ + + + + + + + +')
next()
})
// Back hook, jump after callback
router.afterEach((to, from) = > {
// to and from are both route objects.
console.log('-- -- -- -- -- -- -- -- -- --')})Copy the code
Complete navigation parsing process
- Navigation is triggered.
- Call the beforeRouteLeave guard in the deactivated component.
- Call the global beforeEach guard.
- Call the beforeRouteUpdate guard (2.2+) in the reused component.
- Call beforeEnter in routing configuration.
- Parse the asynchronous routing component.
- Call beforeRouteEnter in the activated component.
- Call the global beforeResolve guard (2.5+).
- Navigation confirmed.
- Call the global afterEach hook.
- Trigger a DOM update.
- Call the callback passed to Next in the beforeRouteEnter guard, and the created component instance is passed in as an argument to the callback.
Thank you for reading, if you are helpful, welcome to pay attention to “CRMEB” nuggets. Code cloud has our open source mall project, knowledge payment project, JAVA version of the full open source mall system, study and study welcome to use, the old iron easily point a star bai, the boss reward fifty cents, points you twenty-five cents, 😂😂 pay attention to us to keep in touch!