一、
安装npm
npm install vue-router@4
Yarn安装:
yarn add vue-router@4
官网:https://router.vuejs.org/zh/guide
二、声明式使用:
1、定义路由路径和要跳转的组件:
过程:首先定一个目录router并新建一个文件index.js。
其次在main.js引入并使用vue实例app.user(router)。
再次在App.vue中加入<router-view/>用于插入跳转的视图。
***在App.vue的setup中加入mounted方法用于在组件展示时首先展示登陆页面。
三、创建步骤:
首先在src下创建router目录并创建index.js文件:
import { createRouter, createWebHashHistory } from 'vue-router'
//此处配置了两个示例路由,一个是登陆,一个是登录后跳转的主页
const routes = [
{ path: '/',
name:'login',
component: () => import('@/components/login/Login.vue'),
meta: { title_cn: '登录', title_en: 'Login' },
},
{ path: '/login',
name:'login',
component: () => import('@/components/login/Login.vue'),
meta: { title_cn: '登录', title_en: 'Login' },
},
{ path: '/main',
name:'main',
component: () => import('@/components/dashboard/Cockpit.vue')},
]
//创建路由对象并导出
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
})
export default router
然后将该定义引入到main.js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
//vue使用路由
app.use(ElementPlus)
.use(router)
.mount('#app')
最后在App.vue中引入路由并设置在组件加载完成后默认跳转到登陆页面:
<template>
<!-- <img alt="logo" src="./assets/fav.png" style="margin-left: 0%;"> -->
<router-view></router-view>
</template>
<script>
import { reactive, watch } from 'vue'
import router from './router/index.js'
export default {
name: 'App',
mounted() {
// 做一些权限校验的工作,默认跳转到登陆页面
router.push('/login')
},
setup() {
}
}
</script>
如此一个简单的跳转即可实现。