Vue study notes---------Vue core (3)
routing
- Understanding: A route is a set of mapping relationships (key-value), and multiple routes need to be managed by a router.
- Front-end routing: key is the path, and value is the component.
1. Basic use
-
Install vue-router, command: npm i vue-router
-
Application plugin: Vue.use(VueRouter)
-
Write router configuration items:
//Introduce VueRouter import VueRouter from 'vue-router' //Introduce the route component import About from '../components/About' import Home from '../components/Home' //Create router instance objects to manage groups of routing rules const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //expose router export default router
-
Implement switching (active-class can configure the highlight style)
<router-link active-class="active" to="/about">About</router-link>
-
Specify placements
<router-view></router-view>
2. A few notes
- Routing components are usually stored in the pages folder, and general components are usually stored in the components folder.
- By switching, the "hidden" routing components are destroyed by default, and can be mounted when needed.
- Each component has its own $route property, which stores its own routing information.
- The entire application has only one router, which can be obtained through the component's $router property.
3. Multi-level routing (multi-level routing)
-
To configure routing rules, use the children configuration item:
routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //Configure child routing through children { path:'news', //Do not write here: /news component:News }, { path:'message',//Do not write here: /message component:Message } ] } ]
-
Jump (to write the full path):
<router-link to="/home/news">News</router-link>
4. The query parameter of the route
-
pass parameters
<!-- jump and carry query parameter, to string notation --> <router-link :to="/home/message/detail?id=666&title=Hello">jump</router-link> <!-- jump and carry query parameter, to object notation --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'Hello' } }" >jump</router-link>
-
Receive parameters:
$route.query.id $route.query.title
5. Named Routes
-
Function: It can simplify the jump of the route.
-
how to use
-
Name the route:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //name the route path:'welcome', component:Hello, } ] } ] }
-
Simplified jump:
<!--Before simplifying, you need to write the full path --> <router-link to="/demo/test/welcome">jump</router-link> <!--After simplification, jump directly by name --> <router-link :to="{name:'hello'}">jump</router-link> <!--Simplified writing with passing parameters --> <router-link :to="{ name:'hello', query:{ id:666, title:'Hello' } }" >jump</router-link>
-
6. The params parameter of the route
-
Configure the route, declare to receive the params parameter
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //Use placeholder declarations to receive params parameters component:Detail } ] } ] }
-
pass parameters
<!-- jump and carry params parameter, to string notation --> <router-link :to="/home/message/detail/666/Hello">jump</router-link> <!-- jump and carry params parameter, to object notation --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'Hello' } }" >jump</router-link>
Special attention: When the route carries the params parameter, if the object writing of to is used, the path configuration item cannot be used, and the name configuration must be used!
-
Receive parameters:
$route.params.id $route.params.title
7. Routing props configuration
β Function: Make it easier for routing components to receive parameters
{ name:'xiangqing', path:'detail/:id', component:Detail, //The first way of writing: the props value is an object, and all key-value combinations in the object will eventually be passed to the Detail component through props // props:{a:900} //The second way of writing: the props value is a boolean value, and the boolean value is true, then all the params parameters received by the route are passed to the Detail component through props // props:true //The third way of writing: the props value is a function, and each set of key-value s ββin the object returned by the function will be passed to the Detail component through props props(route){ return { id:route.query.id, title:route.query.title } } }
8. replace attribute of <router link>
- Role: control the mode of operating browser history when routing jumps
- There are two ways to write the browser's history: push and replace, push is to append the history, and replace is to replace the current record. When the route jumps, the default is push
- How to start the replace mode: <router link replace........ > News</router-link>
9. Programmatic Routing Navigation
-
Function: realize route jump without the help of <router link>, making route jump more flexible
-
Specific code:
//Two API s for $router pushMsg(m){ this.$router.push({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, replaceMsg(m){ this.$router.replace({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, this.$router.forward() //go ahead this.$router.back() //back this.$router.go(number) //Can go forward or backward
10. Cache routing components
-
Function: Keep the routing components that are not displayed mounted and not destroyed.
-
Specific code:
<keep-alive include="News"> <router-view></router-view> </keep-alive> //cache multiple <keep-alive include="['News','Message']"> <router-view></router-view> </keep-alive>
11. Two new lifecycle hooks
-
Role: Two hooks unique to the routing component, used to capture the activation state of the routing component.
-
Specific name:
- Fired when the activated routing component is activated.
- Triggered when the deactivated routing component is deactivated.
activated() { console.log('i activated') this.timer = setInterval(() => { console.log('@') },1000) }, deactivated() { console.log('I sent') clearInterval(this.timer) },
12. Routing guard
-
Role: Permission control for routing
-
Categories: global guards, exclusive guards, in-component guards
-
Global Guard:
//Global front guard: executed at initialization, executed before each route switch router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //Determine whether the current route needs permission control if(localStorage.getItem('name') === 'lai'){ //Specific rules for access control next() //release }else{ alert('No permission to view') // next({name:'guanyu'}) } }else{ next() //release } }) //Global post guard: executed at initialization, executed after each route switch router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //Modify the title of the page }else{ document.title = 'vue_test' } })
-
Exclusive Guard:
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //Determine whether the current route needs permission control if(localStorage.getItem('name') === 'lai'){ next() }else{ alert('No permission to view') // next({name:'guanyu'}) } }else{ next() } }
-
In-component guards:
//Entry guard: Called when entering the component through routing rules beforeRouteEnter (to, from, next) { console.log('I'm an in-component route guard') if(to.meta.isAuth){ if(localStorage.getItem('name') === 'lai'){ next() }else{ alert('Username is incorrect') } }else{ next() } }, //Leaving guard: Called when leaving the component through routing rules beforeRouteLeave (to, from, next) { next() }
13. Two working modes of the router
- For a url, what is the hash value? —— # and the content after it is the hash value.
- The hash value will not be included in the HTTP request, that is: the hash value will not be brought to the server.
- hash mode:
- There is always a # in the address, which is not beautiful.
- If the address is shared through a third-party mobile app in the future, if the app verification is strict, the address will be marked as illegal.
- Compatibility is better.
- history mode:
- The address is clean and beautiful.
- Compatibility is slightly worse than hash mode.
- When the application is deployed and launched, the support of the back-end personnel is required to solve the problem of refreshing the page server 404.
- Install connect-history-api-fallback to solve