Vue Router is the official route manager of vue.js. Its deep integration with vue.js core makes building single-page applications a breeze. The features included are:
The basic concept
- Nested routing/view chart
- Modular, component-based routing configuration
- Route parameters, queries, and wildcards
- View transition effect based on vue. js transition system
- Fine-grained navigation control
- Links with automatically activated CSS classes
- HTML5 historical mode or Hash mode is automatically degraded in IE9
- Custom scroll bar behavior
This is the official introduction of VUe-Router. Next, I summarize the relevant knowledge of vue-Router that I usually use. It is suitable for beginners
Before using vue-Router, we first need to integrate it into the Vue scaffolding,
(Note: This article assumes that you have vue-CLI installed by default.)
Vue – the router installation
npm install vue-router --save
Vue – the router to use
Write the following code in the SRC /router/index.js file
import Vue from 'vue'
import VueRouter from 'vue-router'
// Register VueRouter in vUE
Vue.use(VueRouter);
// Import the component of the route mapping
// Common import mode
import comA from '@components/comA'
// Lazy loading is required (lazy loading means that you don't load all the resources at the beginning and wait too long, but when you switch the navigation, the resources in the related components will be loaded)
const comB = resolve= >require(['@components/comB'],resolve);
// Then write out the route mapping
const routes = [
{
path:'/'.name:'home'.component:home,
},
{
path:'/about'.name:'about'.component:about,
children:[
{
path:'aboutA' // Path :'/about/aboutA'}, {path:'aboutB',}]}]Copy the code
This is the simpler and more complete structure, minus (parameters and hooks, explained later). After writing the mapping, create the Router instance and pass the mapping to it
const router = new VueRouter({
routes
})
// Note that the global routing hook is written to the router instance as follows
router.beforeEach((to, from, next) = >{... next(); })Copy the code
Vue – the pattern of the router
By default, the vue router uses hash mode, which can be used to redirect a route to a router with a number of hashtags. This makes full use of the history.pushStateAPI to redirect a URL without reloading the page. This improves the user experience. However, when you go directly to www.root.com/home/page1, the browser will actually request the address, and if the back end is not configured, it will return 404, which is awkward, so be sure to work with the back end.
The basic pattern looks like this
const router = new VueRouter({
mode:"history",
routes
})
Copy the code
Routing and the cords
There are two types of routing parameters: Params and Query. Let’s take a look at Params
const User = {
template: '<div>{{$route.params.id}}</div>'
}
const router = new VueRouter({
routes: [
// Dynamic path parameters start with a colon
{ path: '/user/:id'.component: User }
]
})
Copy the code
Using $route within a component causes the component to be highly coupled so that the component can only be used at a specific URL. Its flexibility is limited, so you can decouple them using props,
const User = {
props: ['id'].template:`<div>{{id}}</div>`
}
const router = new VueRouter({
routes:[
{
path:'/user/:id'.component:User,
props:true
},
// For routes that contain named views, you must add props options for each named route, as follows
{
path:'/user/:id'.components: {default:User,sidebar:SideBar},
props: {default:true.sidebar:false}}}])Copy the code
This greatly increases the flexibility of components, making them easier to reuse and test
Params and query
Query is used like this
/ / the refs
this.$router.push({
name:'home'.query: {id:id
}
})
// Accept arguments
this.route.query.id
Copy the code
params
Much like query,
/ / the refs
this.$router.push({
name:'home'.params: {id:id
}
})
// Accept arguments
this.route.params.id
Copy the code
It is important to note that you should not use path when using Params, because params itself is a component of the path dynamic path.
For consistency, both Query and Params pass arguments using namA to distinguish them.
Position of parameter
This.$router.push and router-link to have the same parameter type. The following
< the router - the link to: "/ home" > < / router - the link > / / equivalent to this. $router. Push ("/home "); { name:"home", path:'/home/:id', Componet :Home} <router-link to:"{name:" Home ",params:{id:"lala"}}" // equivalent to this.$router-link ({name:" Home ",params:{id:"lala"}}") params:{ id:"lala" } })Copy the code
This.$router. Push ();
Routing hooks
Global routing hook
beforeEach
and afterEach
const router = new VueRouter({ ... }) // The global routing hook is on the router instance. Router.beforeeach ((to, from, next)=>{// To to reach the routing object // From the destination routing object // next() make the next step // next(false) interrupt the current jump, //next('/') or next({name:"home",params:{}})}) router. AfterEach ((to,from)=>{... // Navigation is finished, so no next})Copy the code
A hook on a route mapping relationship
Basically the same as global routing hooks
beforeEnter
and afterEnter
const router = new VueRouter({
routes:[
{ name:home,
path:'/home'.component:Home,
beforeEnter:(to,from, next) = >{... },afterEnter:(to, from) = >{... }}}])Copy the code
A hook within a component
BeforeRouterEnter and beforeRouterUpdate(2.2 add) and beforeRouterLeave
export default{
data(){
return{... } }, beforeRouteEnter (to,from, next){
// This cannot be called because the navigation has not been confirmed and the instance has not been created before using this
},
beforeRouteUpdate(to,from,next){
// This function can be used in dynamic routes such as /home/:id, where the component remains the same due to the id change
// At this point the instance has been created, so this is ready for the stage
},
beforeRouteLeave(to,from,next){
// This function is triggered when navigating away from the component route
// Access this}}Copy the code
Vue-router in Vue2.0 + TS
If you want to use vue2.0 + ts, you need to register hooks as follows
Component.registerHooks(['beforeRouteEnter', 'beforeRouteLeave', 'beforeRouteUpdate']);
In-component use
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator';
// Register the hook
Component.registerHooks(['beforeRouteEnter'.'beforeRouteLeave'.'beforeRouteUpdate']);
@Component({})
class PageReply extends Vue {
beforeRouteEnter(to, from, next) {
next();
}
beforeRouteLeave(to, from, next) { next(); }}Copy the code