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: the key is the path, and the value is the component.
1. Basic use
-
Install vue-router, command:
npm i vue-router
-
Apply plugin:
Vue.use(VueRouter)
-
Write router configuration items:
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 组件 import About from '../components/About' import Home from '../components/Home' //创建router实例对象,去管理一组一组的路由规则 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router
-
Implement switching (active-class can configure highlighting style)
<router-link active-class="active" to="/about">About</router-link>
-
target placements
<router-view></router-view>
2. A few points for attention
- Routing components are usually stored in
pages
folders, and general components are usually stored incomponents
folders. - By switching, the "hidden" routing components are destroyed by default, and then mounted when needed.
- Each component has its own
$route
properties, which store its own routing information. - The entire application has only one router, which can
$router
be obtained through the properties of the component.
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:[ //通过children配置子级路由 { path:'news', //此处一定不要写:/news component:News }, { path:'message',//此处一定不要写:/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
<!-- 跳转并携带query参数,to的字符串写法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link> <!-- 跳转并携带query参数,to的对象写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳转</router-link>
-
Receive parameters:
$route.query.id $route.query.title
5. Naming Routes
-
Function: It can simplify the routing jump.
-
how to use
-
Give the route a name:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ] }
-
Simplified jump:
<!--简化前,需要写完整的路径 --> <router-link to="/demo/test/welcome">跳转</router-link> <!--简化后,直接通过名字跳转 --> <router-link :to="{name:'hello'}">跳转</router-link> <!--简化写法配合传递参数 --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳转</router-link>
-
6. The params parameter of the route
-
Configure routing, declare to receive params parameters
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
-
pass parameters
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="/home/message/detail/666/你好">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>
Special attention: When the route carries params parameters, if you use the object writing method of to, you cannot use the path configuration item, you must use the name configuration!
-
Receive parameters:
$route.params.id $route.params.title
7. Routing props configuration
Role: Make it easier for routing components to receive parameters
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}
8. <router-link>
The replace attribute
- Role: control the mode of operating browser history when routing jumps
- There are two ways to write the history of the browser:
push
and respectivelyreplace
,push
which is to append the history record, andreplace
is to replace the current record. When the route jumps, the default ispush
- How to turn on
replace
the mode:<router-link replace .......>News</router-link>
9. Programmatic Routing Navigation
-
<router-link>
Function: Make routing jumps more flexible without the help of routing jumps -
Specific encoding:
//$router的两个API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前进 this.$router.back() //后退 this.$router.go() //可前进也可后退
10. Cache Routing Components
-
Function: keep the routing components that are not displayed mounted and not destroyed.
-
Specific encoding:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
11. Two new lifecycle hooks
- Function: Two hooks unique to routing components, used to capture the activation status of routing components.
- specific name:
activated
Fired when the routing component is activated.deactivated
Triggered when the routing component is deactivated.
12. Route Guard
-
Role: to control the authority of the route
-
Category: global guard, exclusive guard, component guard
-
Global Guard:
//全局前置守卫:初始化时执行、每次路由切换前执行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则 next() //放行 }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守卫:初始化时执行、每次路由切换后执行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改网页的title }else{ document.title = 'vue_test' } })
-
Exclusive Guard:
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() } }
-
Guards inside the component:
//进入守卫:通过路由规则,进入该组件时被调用 beforeRouteEnter (to, from, next) { }, //离开守卫:通过路由规则,离开该组件时被调用 beforeRouteLeave (to, from, 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 # sign 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, it needs the support of the back-end personnel to solve the problem of refreshing the page server 404.
©Excerpted from a full set of Vue2.0+Vue3.0 tutorials by Zhang Tianyu of Shang Silicon Valley丨Routing courseware