Vue3中路由基本使用
引入路由
1、首先需要在项目中使用下面的命令引入路由
npm install vue-router@4
2、创建一个router文件夹,存放和路由相关的代码,创建index.js
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
//定义路由
{
//路由path
path: '/el_test',
//路由name
name: '/el_test',
//路由组件
component: () => import('@/components/el_test.vue')
},
{
path: '/home',
name: '/home',
component: () => import('@/components/HelloWorld.vue')
}
]
// 创建路由对象
const router = createRouter({
//hash模式的路由
history: createWebHashHistory(),
routes
})
export default router
3、在main.js中导入路由组件,并挂载到根实例上
import router from '@/router/index'
createApp(App)
//挂载ElementPlus
.use(ElementPlus)
//挂载路由
.use(router)
.mount('#app');
测试
在App.Vue中使用router-link组件测试路由是否生效。router-link在页面上会显示一个超链接,点击超链接会跳转到to属性指定的页面,而页面显示的内容由路由中的component属性指定。
<template>
<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<router-link to="/home">go to home</router-link>
<router-link to="/el_test">go to ElTest</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</template>
效果如下: