Get started
HTML
<script src="/vue/dist/"></script> <script src="/vue-router/dist/"></script> <div > <h1>Hello App!</h1> <p> <!-- use router-link Components to Navigate. --> <!-- By passing `to` Properties specify link. --> <!-- <router-link> By default it will be rendered into one `<a>` Label --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- Routing exit --> <!-- The component that the route matches will be rendered here nBuilt-in components--> <router-view></router-view> </div>
JavaScript
// 0. If you use a modular mechanism to import Vue and VueRouter, you need to call (VueRouter) // 1. Define (routing) components.// You can enter from other filesconst Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } // 2. Define the route// Each route should map a component. Where "component" can be// Component constructor created by ()// Or, just a component configuration object.// We will discuss nested routing later.const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] // 3. Create a router instance and pass the `routes` configuration// You can also pass on other configuration parameters, but it's that simple first.const router = new VueRouter({ routes // (Abbreviation) equivalent to routes: routes}) // 4. Create and mount the root instance.// Remember to inject routes through router configuration parameters.// This allows the entire application to have routing functionsconst app = new Vue({ router }).$mount('#app') // Now,The application has been launched!
By injecting the router, we can access the router through this.$router within any component, or the current route through this.$route:
export default { computed: { username () { // We will see what `params` is soon return this.$ } }, methods: { goBack () { > 1 ? this.$(-1) : this.$('/') } } }
routes options (Array)
redirect (redirect)
//A will jump to /bconst router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' } ] }) //The redirected target can also be a named route:const router = new VueRouter({ routes: [ { path: '/a', redirect: { name: 'foo' }} ] }) //Even a method that dynamically returns the redirect target:const router = new VueRouter({ routes: [ { path: '/a', redirect: to => { // Method reception Target routing as parameter // return redirected string path/path object }} ] })
Named routes
export default [ { path:'/', redirect:'/app' //Default jump route }, { path: '/app', //Route naming, can be used for jump name: 'app', } ] // Can be used for jump<router-link :to="{name:'app'}">app</router-link>
Routing meta information
When defining routes, you can configure the meta field:
export default [ { path:'/', redirect:'/app' //Default jump route }, { path: '/app', //**Meta tags equivalent to HTML** meta: { title: 'this is app', description: 'asdasd' }, } ]
Nested routing
export default [ { path:'/', redirect:'/app' //Default jump route }, { path: '/app', //Sub-routing Match /app/test children: [ { path: 'test', component: Login } ] } ]
Routing component parameters
export default [ { path:'/', redirect:'/app' //Default jump route }, { path: '/app/:id', // /app/xxx, this value can be obtained through $ inside the component // The following parameters will be passed to the component Todozhong through props //Boolean mode props: true, //Object Mode props:{id:456} //Function mode props: (route) => ({ id: }), component: Todo, } ]
mode option(string)
vue-router default hash mode - uses the hash of the URL to simulate a complete URL, so when the URL changes, the page will not reload.
If you don't want an ugly hash, we can use the routing history pattern, which makes full use of the API to complete URL jumps without reloading the page.
const router = new VueRouter({ mode: 'history', routes: [...] })
To play this mode well, it also requires backend configuration support.
base(string)
The base path to be applied. For example, if the entire single page application service is under /app/, then base should be set to "/app/"
return new Router({ routes, mode: 'history',//Default hash# base: '/base/', //In front of the path, /base/, base path will be added })
linkActiveClass(string)
Default value: "router-link-active"
The default "Activate class class name" for global configuration <router-link>.
return new Router({ routes, mode: 'history',//Default hash# base: '/base/', //In front of the path, /base/, base path will be added // Click on the Calss name linkActiveClass: 'active-link', //Match to one of the subsets linkExactActiveClass: 'exact-active-link',//Exact match })
linkExactActiveClass(string)
Default value: "router-link-exact-active"
Global configuration <router-link> The default class that is activated accurately.
scrollBehavior(Function)
Whether the route is scrolled after jumping
export default () => { return new Router({ routes, mode: 'history',//Default hash# base: '/base/', //In front of the path, /base/, base path will be added //Does the page need to be scrolled if it is redirected /* to:Towards route, complete route object from:Source route savedPosition:Save scroll position */ scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }, }) }
parseQuery / stringifyQuery (Function)
/every timeimportWill create onerouter,避免every time都是同一个router export default () => { return new Router({ routes, mode: 'history',//Default hash# base: '/base/', //In front of the path, /base/, base path will be added // Parameters after the route?a=2&b=3,string->object parseQuery (query) { }, //object->string stringifyQuery (obj) { } }) }
fallback(boolean)
When the browser does not support it controls whether the route should fall back to hash mode. The default value is true.
If set to false, the page will be refreshed after jumping, which is equivalent to multi-page application
<router-link>
Transitional effect
<router-view> is a basic dynamic component, so we can add some transition effects to it using the <transition> component:
<transition> <router-view></router-view> </transition>
Advanced Usage
Named Views
<router-view class="view one"></router-view> <router-view class="view two" name="a"></router-view> <router-view class="view three" name="b"></router-view> const router = new VueRouter({ routes: [ { path: '/', components: { //Default component default: Foo, //Name component a: Bar, b: Baz } } ] })
Navigation Guard
Global Guard
import Vue from 'vue' import VueRouter from 'vue-router' import App from './' import './assets/styles/' // const root = ('div') // (root) import createRouter from './config/router' (VueRouter) const router = createRouter() // Global Navigation Guard (Hook) // Verify that some users are logged in((to, from, next) => { ('before each invoked') next() // if ( === '/app') { // next({ path: '/login' }) // (' :'+ ) // } else { // next() // } }) ((to, from, next) => { ('before resolve invoked') next() }) // Trigger after each jump((to, from) => { ('after each invoked') }) new Vue({ router, render: (h) => h(App) }).$mount("#root")
The guards exclusively for routes
You can directly define the beforeEnter guard on the routing configuration:
export default [ { path:'/', redirect:'/app' //Default jump route }, { path: '/app', // The guard hook exclusive to the route beforeEnter(to, from, next) { ('app route before enter') next() } component: Todo, } ]
Guards within components
export default { //Before coming in beforeRouteEnter(to, from, next) { // No! able! Get component instance `this` // Because the component instance has not been created before the guard has been executed ("todo before enter", this); //todo before enter undefined //Can access component instances by passing a callback to next. When the navigation is confirmed, the callback is executed and the component instance is used as a parameter to the callback method. next(vm => { // Access component instances through `vm` ("after enter is ", ); }); }, // When it is updated beforeRouteUpdate(to, from, next) { ("todo update enter"); next(); }, //Route departure beforeRouteLeave(to, from, next) { ("todo leave enter"); const answer = ('Do you really want to leave? you have unsaved changes!') if (answer) { next() } else { //Cancel via next(false). next(false) } }, props:['id'], components: { Item, Tabs }, mounted() { () }, };
Lazy route loading
refer to:Lazy route loading
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.