vue-router的简单使用

一、

安装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>

如此一个简单的跳转即可实现。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值