使用 vue3 配置路由,步骤如下
1、安装路由
npm install vue-router@4

2、新建页面
在src目录下新建 view 目录,然后在view目录下创建 A.vue 和 B.vue 两个 vue页面文件。
A.vue内容
<template> <div>A</div> </template>
B.vue内容
<template> <div>B</div> </template>
3、创建路由配置文件
在src目录下新建 router目录,然后在 router目录下新建 index.js 和 routes.js 文件
index.js 文件内容如下
import {createRouter, createWebHistory} from 'vue-router' import routes from './routes' const router = createRouter({ history: createWebHistory(), routes }) export default router
routes.js 文件内容如下
const routes = [ { name: 'a', path: '/a', component: () => import('@/view/A') }, { name: 'b', path: '/b', component: () => import('@/view/B') }, ]; export default routes
在 main.js中配置路由
import { createApp } from 'vue' import App from './App.vue' import router from './router/index' //注意use要在mount之前 createApp(App).use(router).mount('#app')
4、添加 router-view
笔者这里为了演示在 app.vue文件中添加,读者可根据自己的情况进行添加
<template> <HelloWorld msg="Welcome to Your Vue.js App"/> <router-view></router-view> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld } } </script> <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>
HelloWorld.vue 内容如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <div> <button @click="show('a')">A页面</button> <button @click="show('b')">B页面</button> </div> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, methods: { show(index) { if(index == 'a') { this.$router.push('/a') } if(index == 'b') { this.$router.push('/b') } } } } </script>
路由控制在 HelloWorld.vue文件中, 使用 this.$router.push()方法进行路由跳转
5、运行效果
