安装完成的项目,发现没有路由文件,我们的项目肯定会用到路由,所以直接安装路由
一、目录结构
二、安装router
2.1 执行命令
npm install vue-router@4 -S
2.2 安装完成
2.3 进入项目,创建router目录,再去创建index.js
三、配置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;
四、在src目录新建views/Home.vue和About.vue
Home.vue和About.vue随便写入点内容即可
五、App.vue文件内容修改
5.1 原本为:
<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>
5.2 修改成:
<template>
<router-view />
</template>
六、main.js挂载使用router
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
createApp(App).use(router).mount('#app')
相关作者
- 获取点赞0
- 文章阅读量133
评论()