VueRouter Basic tutorial series 🎉


The instance

Create a basic routing instance object.

JavaScript:

// Create a component object
const About = {
    name: 'About'.template: "<h1>This is About Page.</h1>".mounted(){
        console.log(this.$router); }};const Profile = {
    name: 'Profile'.template: '<h1>This is Profile Page.</h1>'.mounted(){
        console.log(this.$route); }};// Create a routing configuration and map the component to the corresponding routing path.
const routes = [
    {
        path: '/about'.component: About
    },
    {
        path: '/profile'.component: Profile
    }
];

// Create a route instance object
const router = VueRouter.createRouter({
    routes,
    history: VueRouter.createWebHashHistory()
});

// Create a Vue application.
const app = Vue.createApp({});

// Inject the route instance object as Options into the application global.
// All component instances can access the router object through 'this.$router' without tedious import/export.
app.use(router);

app.mount('#app');
Copy the code

HTML:

<div id="app">
    <ul>
        <li><router-link to="/about">Go About</router-link></li>
        <li><router-link to="/profile">Go Profile</router-link></li>
    </ul>
    <hr/>
    <router-view />
</div>
Copy the code

Routing patterns

  • Using hash modecreateWebHashHistory()Method creation.
  • HTML5 History mode is usedcreateWebHistory()Method creation.

Render exit of route

VueRouter’s custom component

defines the render exit of the routing view. The VueRouter allows for multiple route rendering exits, which is mainly used in scenarios where routes are nested and named views.

Route navigation mode

VueRouter provides two route navigation modes, declarative and imperative.

Non-replacement navigation adds a new record to the browser’s history stack, so you can use the browser’s forward/back buttons to move up and down the stack sequentially.

declarative imperative
<router-link to="..." >Link</router-link> router.push()

You can use the REPLACE attribute (declarative) or the REPLACE method (imperative) for alternative routing navigation. No previous visits will be recorded in the browser’s history stack, so the browser’s back button will be disabled (unable to return the last history correctly).

declarative imperative
<router-link to="..." replace>Link</router-link> router.replace()

The parameters (destination address) received by both declarative and imperative routes are the same.

Specifically, the declarative to=”…” Attribute, which takes the same parameters as the imperative push() or replace() methods.

const routes = [
    {
        path: '/user/:id'.component: { template: '<div><h1>{{$route.params.id}}</h1><router-view /></div>' },
        children: [{path: 'profile'.component: { template: '<p>profile</p>'}}]}];Copy the code

Command:


// The value is a string
this.$router.replace('/user/123/profile');

// Object value
this.$router.push({
    path:'/user/123/profile'.hash:'#team'.query: {group:1}});// /user/123/profile? group=1#team
Copy the code

Declarative:

<router-link to="/user/123/profile">link user profile</router-link>
<router-link :to="{ path:'/user/123/profile', hash:'#team', query:{group:1} }">link user profile</router-link>
Copy the code

In addition to the push and replace methods, you can use router.go() to span history; Router.forward () and router.back() can be used to go forward or back. They are both mimics of the Window.history API.

It is worth noting that the navigation methods of the Vue Router (push, replace, Go) work consistently regardless of what history configuration is passed when creating the Router instance.

Route instance object

In a future context, we will agree that routing instance objects should also not be called “router” objects. The router comes with the install method, so it can be globally registered by the app.use(router) method as a plug-in. When the router is successfully registered, we can use this.$router on each component instance to access the router object, which is the same as the instance created with createRouter(). The benefit of this call is to reduce frequent imports/exports.

Remember, this.$router is exactly the same as using the router instance created directly through createRouter.

The this.$router instance object stores all routing-related operations and information about all routes.

methods instructions
addRoute Add a new route record as a child route of an existing route.
afterEach Add a global rear guard.
back Imperative navigation (back)
beforeEach Add a global front hook.
beforeResolve Add a global resolution hook.
forward Imperative navigation (forward)
getRoutes Gets a complete list of all routing records (equivalent to returning the entireroutesConfiguration).
go Imperative navigation (jump to the specified index in the history stack)
hasRoute Check whether a route with the specified name exists.
install Router registration method.
isReady Check whether the router is initialized.
onError Router error handler.
push Imperative navigation (appending the history stack)
removeRoute Delete an existing route by name.
replace Imperative navigation (way to replace the history stack)
resolve Resolve the target location.
attribute instructions
currentRoute Route information object corresponding to the current route.
options The original configuration object passed when the Router was created. Read-only.

In addition, VueRouter provides another this.$Route object that stores only the currently active routes.

attribute instructions
fullPath The complete routing address, which containspath,query,hash
hash Saves the hash portion extracted from the URL. Always start with #. If not, an empty string' '.
query Saves “query parameters” extracted from the URL, always starting with? Start, if not empty object{}.
params Saved frompathextracted“Path Parameters”
matched Holds all matched routes in an array.
meta Arbitrary data attached to all matched records from parent to child merge (non-recursive).
name The name of the route record.
path Currently routedpath
href The functions andfullPathPretty much the same.
redirectedFrom The value is used to save the redirection source ADDRESS if the redirection operation is performed; if the redirection operation is not performed, the value isundefined.