要实现的效果如下(注意URL的改变):
流程:
1.新建一个工程,依次完成以下步骤
npm init vite-app vue3Router01
cd vue3Router01
npm intall
npm install vue-router@next
npm run dev
2.打开App.vue,编写如下代码:
<template>
<div>
<h1>Hello App!</h1>
<p>
<!-- use the router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
3.在vue3Router01>src文件夹中新建文件夹router,并在router中新建index.js,如下图:
4.在index.js中编写如下代码:
import {createRouter,createWebHashHistory} from 'vue-router'
// 1. Define route components.
// These can be imported from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: createWebHashHistory(),
routes, // short for `routes: routes`
})
export default router
5.在vue3Router01>src>main.js中编写如下代码:
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from "./router";
const app = createApp(App)
// 使用路由
app.use(router)
app.mount('#app')