1.安装
yarn add vue-router@4
2.配置
新建views文件夹和两个测试页面page1.vue和page2.vue;
新建router文件夹,然后再文件夹中新建index.js,内容如下:(如果想使用@路径,请参见Vue3系列第八章)
import { createRouter, createWebHistory } from 'vue-router'
const routerHistory = createWebHistory()
const router = createRouter({
history: routerHistory,
routes: [
{
path: '/',
component: () => import('../components/HelloWorld.vue')
}, {
path: '/page1',
component: () => import('../views/page1.vue')
}, {
path: '/page2',
component: () => import('../views/page2.vue')
}
]
})
export default router
3.注册
修改main.js如下
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
4.修改App.vue如下(将HelloWorld组件换成router-view)【注意注意注意:App.vue的style中设置了top外边距margin-top:60px,记得改成0px】
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
</script>
<template>
<router-view></router-view>
</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>
文件架构如下: