The installation

yarn add vue-router@4
Copy the code

use

router.js

import { createRouter, createWebHistory } from "vue-router";

import Home from "./views/Home.vue";

const routes = [
  { path: "/".component: Home },
  { path: "/about".component: () = > import("./views/About.vue")}];const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;
Copy the code

main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App);
app.use(router);
app.mount("#app");
Copy the code

App.vue

<template> <h1>Hello App! </h1> <p> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <router-view></router-view> </template> <script> export default {}; </script>Copy the code

A little tip

If your App. Vue template only has
, you can put

directly into index.html. But this requires using native ESM or a Vue project built directly from Vite.

For example: index. HTML

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app">
      <router-view></router-view>
    </div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
Copy the code

Then remove app.vue from main.js

main.js

import { createApp } from "vue";
// import App from "./App.vue";
import router from "./router";

// const app = createApp(App);
const app = createApp({});
app.use(router);
app.mount("#app");
Copy the code

Done! 😀 is convenient and easy to use