1.首先下载vue-router依赖包
npm i vue-router
yarn add vue-router
2. 在根目录下创建router文件夹并在其下创建index.js,代码如下
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: "/",
redirect: "/home",
component: () => import("@/views/Home/index.vue")
},
{
// 首页
path: "/home",
name: "home",
component: () => import("@/views/Home/index.vue"),
meta: {
title: "首页",
},
}
]
const router = createRouter({
history: createWebHashHistory(),
routes: routes,
});
export default router;
注:我这里使用的是哈希路由 若使用历史路由 进行导入 createWebHistory
import { createRouter, createWebHistory } from "vue-router";
3.在main.js下引入router
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App);
app
.use(router)
.mount('#app')
4.最后在App.vue下加入<router-view/>
<script setup>
</script>
<template>
<router-view />
</template>
<style scoped>
</style>