1.安装router
执行命令
npm install vue-router@4 -S
进入项目,创建router目录,再去创建index.js
2.配置src/router/index.js文件内容
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
3.在src目录新建views/Home.vue和About.vue
Home.vue和About.vue随便写入点内容即可
3.App.vue文件内容修改
原本为:
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
修改为
<template>
<router-view />
</template>
4.main.js挂载使用router
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
createApp(App).use(router).mount('#app')