【Vue3中Router使用】

news2025/2/25 20:59:45

Vue3中Router使用

  • 1. 安装`vue-router`组件
  • 2. 建两个测试页面
    • 2.1 测试页面`Home.vue`
    • 2.2 测试页面`Category.vue`
  • 3. 创建路由对象
  • 4. 在入口`main.js`中引入`router`
  • 把`App.vue`改成路由页面
  • 5. 测试
    • 5.1 关闭检查解决`ESlint`报错
    • 5.2 改文件名解决`ESlint`检查报错
    • 测试`WebHashHistory` 和`WebHistory`的区别
  • 6. 管理系统的路由尝试
    • 6.1 修改`App.vue`
    • 6.2 创建`Portal.vue`
    • 6.3 创建`Main.vue`
    • 6.4 建登录界面
    • 6.4.1 安装`less`的模块
    • 6.4.2 安装`ElementPlus`的图标
    • 6.4.3 登录页面效果
    • 6.5 修改路由
    • 6.6 测试效果
    • 6.7 遗留问题.

这里的内容是基于前面搭建的环境进行的,自我摸索过程有不对的地方请希望不怜赐教。

1. 安装vue-router组件

Vue3对应的router组件是vue-router,所以执行下面的命令进行安装router组件。

npm install vue-route

2. 建两个测试页面

src目录下创建一个views目录,在目录先建两个页面,用于路由测试。

2.1 测试页面Home.vue

<template>
  <div>
   This is Home Page....
  </div>
</template>
<script>
  export default {
    // name:"Home"
  }
</script>
<style scoped>
</style>

2.2 测试页面Category.vue

<template>
  <div>
    This is Category....
  </div>
</template>
<script>
  export default {
  }
</script>
<style scoped>
</style>

3. 创建路由对象

src目录下创建router文件夹,并在其中创建一个index.js文件, 整体来说就是创建文件src\router\index.js。在文件中编辑内容如下:

import { createRouter, createWebHashHistory } from "vue-router";
import Home from '@/views/Home.vue'
import Category from '@/views/Category.vue'
const routes = [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/category', component: Category },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes, // short for `routes: routes`
})

export default router

createWebHashHistory(),这个应该是采用hash路由的方式,也就是url地址通过#符号进行路由定位。与之对应的是createWebHistory()方法,路由就是一个纯纯的URL地址。后续我们再测试一下。

4. 在入口main.js中引入router

首先是引入router对象

import router from '@/router'

再次需要应用router对象,使用use方法

createApp(App).use(router).mount('#app')

上面一段相对之前增加了use(router)部分。改变之后的main.js如下.

import { createApp } from 'vue'
import App from './App.vue'
import 'element-plus/dist/index.css'
import router from '@/router'
createApp(App).use(router).mount('#app')

PS: 引入router的时候千万不能加中括号写成了import {router} from '@/router'

App.vue改成路由页面

<template>
   <div>
    <div>app</div>
    <router-link to="/home">首页</router-link>
    <router-link to="/category">关于</router-link>
    <router-view></router-view>
   </div>
</template>
<script>
</script>
<style>
</style>

5. 测试

做完上述的一切,其实已经可以对路由功能进行测试了。但是很遗憾,启动的时候报错了,是Eslint代码规范检查报错了,启动不了。报错信息如下.
ESlient报错
报错的核心内容应该是 Component name "Category" should always be multi-word vue/multi-word-component-names。猜测应该就是说我这文件名不规范吧, 要求多个单词做文件名。根据经验来说要么就是遵守规范把文件名改了,要么就是把检查给关了。哪就两种都试试把。

5.1 关闭检查解决ESlint报错

首先在工程根目录下创建.eslintrc.json。文件中的配置内容如下:

{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "plugin:vue/vue3-essential"
    ],
    
    "plugins": [
        "vue"
    ],
    "rules": {
        "import/no-unresolved": "off",
        "import/extensions": "off",
        "import/no-absolute-path": "off",
        "import/no-extraneous-dependencies": "off",
        "vue/no-multiple-template-root": "off",
        "vue/multi-word-component-names": "off",
        "no-param-reassign": [
            "error",
            {
                "props": true,
                "ignorePropertyModificationsFor": [
                    "state",
                    "config"
                ]
            }
        ]
    },
    "settings": {}
}

把文件名的检测规则关掉"vue/multi-word-component-names": "off",.然后就可以启动了.启动之后的控制台信息:
启动控制台
然后访问http://localhost:8080/,因为路由种配置了默认的路由重定向到/home,所以页面会重定向到http://localhost:8080/#/home.得到的测试界面为:
界面
关于首页 是两个超链接,点击可以切换到不同的路由.

5.2 改文件名解决ESlint检查报错

为了验证vue/multi-word-component-names校验报错的问题。为了测试,我们讲该项改为error.

 "vue/multi-word-component-names": "error"

改完之后,再重新运行

npm run serve

错误再次出现.
在这里插入图片描述
接下来我们按照要求吧Home.vue 改成TestHome.vue, Category.vue 改成TestCategory.vue。同时,注意需要将router/index.js的引用部分也改一下。
改后的内容:
在这里插入图片描述

测试WebHashHistoryWebHistory的区别

首先以上的测试使用是是WebHashHistory的方式,所以所以看出路由的方式是#加上路由的地址。 这里再使用下WebHistory的方式,那吧router/index.js中的history换为createWebHistory()router/index.js内容如下:

import { createRouter, createWebHistory } from "vue-router";
import Home from '@/views/TestHome.vue'
import Category from '@/views/TestCategory.vue'
const routes = [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/category', component: Category },
]

const router = createRouter({
    history: createWebHistory(),
    routes, // short for `routes: routes`
})

export default router

改完之后再访问http://locahost:8080,自动跳转到/home的路由,URL地址变为:http://localhost:8080/category。从形式上看就这个差异了。

6. 管理系统的路由尝试

首先管理系统的结构都是,进系统一个登录界面,然后跳转到一个主页面,左边导航,中间主区域就是变化的主要内容。根据这些需求,首先在App.vue这个入口中,应该保留一个router-view标签就OK了。主要用于展示两个路由一个是登录的,另外一个就是主界面。主界面中间区域搞个router-view。最后的造型应该就是如下所示:
router-规划布局

6.1 修改App.vue

<template>
  <div>
    <router-view></router-view>
  </div>
</template>
<script>
</script>
<style>
</style>

6.2 创建Portal.vue

protal页面就是一个测试页面,内容如下

<template>
  <div>Portal............</div>
</template>

<script>
export default {};
</script>

<style>
</style>

6.3 创建Main.vue

<template>
  <div>
    <el-container>
      <el-header>Header</el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu
            default-active="2"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            :router="true"
          >
            <el-sub-menu index="1">
              <template #title>
                <el-icon><location /></el-icon>
                <span>Navigator One</span>
              </template>
              <el-menu-item-group title="Group One">
                <el-menu-item index="1-1" route="/portal">Portal</el-menu-item>
                <el-menu-item index="1-2">item two</el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="Group Two">
                <el-menu-item index="1-3">item three</el-menu-item>
              </el-menu-item-group>
              <el-sub-menu index="1-4">
                <template #title>item four</template>
                <el-menu-item index="1-4-1">item one</el-menu-item>
              </el-sub-menu>
            </el-sub-menu>
            <el-menu-item index="2">
              <el-icon><icon-menu /></el-icon>
              <span>Navigator Two</span>
            </el-menu-item>
            <el-menu-item index="3" disabled>
              <el-icon><document /></el-icon>
              <span>Navigator Three</span>
            </el-menu-item>
            <el-menu-item index="4">
              <el-icon><setting /></el-icon>
              <span>Navigator Four</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
export default {};
</script>
<style scoped>
</style>

中间<el-main>里面route-view是主页填充内容区的路由区域。这里面用了el-menu,el-menu也可以直接用导航,但是需要打开导航所以加属性:router="true",然后挑选了一个item来导航到Protal.
<el-menu-item index="1-1" route="/portal">Portal</el-menu-item>

6.4 建登录界面

创建Login.vue

<template>
  <div class="login">
    <div class="login_form">
      <p>后台管理系统</p>
      <el-form :model="loginForm" ref="loginForm">
        <el-form-item label="" prop="account">
          <el-input
            type="text"
            autocomplete="off"
            v-model="loginForm.account"
            prefix-icon="UserFilled"
            placeholder="请输入用户名"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input
            type="password"
            autocomplete="off"
            v-model="loginForm.password"
            prefix-icon="Lock"
            placeholder="请输入密码"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
const loginForm = reactive({
  account: "",
  password: "",
});
const router = useRouter();
function onSubmit() {
  router.push("/main");
}
</script>
<style scoped lang="less">
.login {
  width: 100%;
  height: 100vh;
  background-image: url("../assets/login/background.jpeg");
  background-size: 100% 100%;
  background-position: center center;
  overflow: auto;
  position: relative;
  .login_form {
    width: 400px;
    height: 360px;
    position: absolute;
    left: 78%;
    top: 50%;
    margin-left: -200px;
    margin-top: -150px;
    padding: 10px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px #ddd;
    .btns {
      display: flex;
      justify-content: flex-end;
    }
  }
  p {
    font-size: 24px;
    text-align: center;
    font-weight: 600;
  }
}
</style>

这里用到了vue-router组件,在点击登录按钮的时候,直接通过router跳转到/main页面。这里要导入一下依赖

import { useRouter } from "vue-router";

6.4.1 安装less的模块

因为这里的样式我用的是less,所以要安装Less的两个工具包

  1. 安装less-loader
npm install less-loader
  1. 安装less
npm install less

6.4.2 安装ElementPlus的图标

这里直接就参照一下ElementPlus官网的的做法就好了。

6.4.3 登录页面效果

登录页面的效果

6.5 修改路由

src/router/index.js的内容修改为:

import { createRouter, createWebHistory } from "vue-router";
const routes = [
    { path: '', redirect: '/login' },
    { path: '/login', component: () => import('@/views/Login.vue') },
    {
        path: '/main',
        component: () => import('@/views/Main.vue'),
        children: [
            { path: '/portal', component: () => import('@/views/Portal.vue') },
        ]
    }
]
const router = createRouter({
    history: createWebHistory(),
    routes, // short for `routes: routes`
})
export default router

6.6 测试效果

  1. 输入URL地址 http://localhost:8080/,自动跳转到登录页面
  2. 点击登录按钮自动跳转到主页面.
  3. 点击左侧导航的Portal页面就直接在中间主要区域打开Portal测试。
    点击Portal跳转到portal页面

6.7 遗留问题.

  1. 登录页面的输入框不能输入。

问题原因是因为 <el-form :model="loginForm" ref="loginForm"> 这里的这个 ref="loginForm"这个应用会导致下面的input框不能输入。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2255166.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AD20 原理图库更新到原理图

一 点击工具&#xff0c;从库更新。快捷键TL 二 点击完成 三 执行变更&#xff0c;最后点击关闭

学习SqlSugar调用达梦数据库的存储过程的基本用法

将之前学习达梦数据库递归用法的SQL语句封装为存储过程&#xff0c;然后使用SqlSugar在C#程序中调用。   打开达梦管理工具&#xff0c;在SCHOOL数据库的存储过程文件夹新建存储过程&#xff0c;这里需注意&#xff0c;存储过程名称及参数名称都需要大写&#xff0c;且参数名…

如何让Google快速收录你的页面?

要让Google更快地收录你的网站内容&#xff0c;首先需要理解“爬虫”这个概念。Google的爬虫是帮助它发现和评估网站内容质量的工具&#xff0c;如果你的页面质量高且更新频率稳定&#xff0c;那么Google爬虫更可能频繁光顾。通常情况下&#xff0c;通过Google Search Console&…

思特奇政·企数智化产品服务平台正式发布,助力运营商政企数智能力跃迁

数字浪潮下,产业数字化进程加速发展,信息服务迎来更广阔的天地,同时也为运营商政企支撑系统提出了更高要求。12月4日,2024数字科技生态大会期间,思特奇正式发布政企数智化产品服务平台,融合应用大数据、AI等新质生产要素,构建集平台服务、精准营销、全周期运营支撑、智慧大脑于…

模型 AITDA(吸引、兴趣、信任、渴望、行动)

系列文章 分享 模型&#xff0c;了解更多&#x1f449; 模型_思维模型目录。吸引、兴趣、信任、渴望、行动 五步曲。 1 模型AITDA的应用 1.1 开源AI智能名片小程序的营销策略 一家企业开发了开源AI智能名片小程序&#xff0c;旨在通过S2B2C模式连接供应商和消费者。该企业采用…

工业—使用Flink处理Kafka中的数据_ProduceRecord1

1 、 使用 Flink 消费 Kafka 中 ProduceRecord 主题的数据,统计在已经检验的产品中,各设备每 5 分钟 生产产品总数,将结果存入Redis 中, key 值为

OpenSSH和OpenSSL升级

需求 centos7.9升级SSH和SSL OpenSSH升级为openssh9.8 OpenSSL升级为openssl-3.4.0 下载openssh最新版本与openssl对应版本 openssh最新版本下载地址 wget https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-9.8p1.tar.gzOpenSSL下载地址 这里下载的是3.4.0 wg…

大语言模型(2)--GPT-1

GPT-1是由OpenAI在2018年推出的第一代生成式预训练模型&#xff08;《Improving Language Understanding by Generative Pre-Training》&#xff09;&#xff0c;它采用了无监督预训练和有监督微调相结合的方法&#xff0c;以增强模型的通用任务求解能力。在此之前&#xff0c;…

IDEA 鼠标悬浮显示方法注释 javaDoc 及配置遇到的问题

方法详情&#xff1a; 鼠标悬浮时的效果&#xff1a; 设置方法&#xff1a; File -> Settings -> Editor -> Code Editing -> Quick Documentation,勾选红框中的选项 可能会遇到的问题&#xff1a; 如果不能选中&#xff0c;如下图 把下图的位置的选中项取消掉 选…

微信小程序实现图片拖拽调换位置效果 -- 开箱即用

在编写类似发布朋友圈功能的功能时&#xff0c;需要实现图片的拖拽排序&#xff0c;删除图片等功能。 一、效果展示 **博主的小程序首页也采用了该示例代码&#xff0c;可以在威信中搜索&#xff1a;我的百宝工具箱 二、示例代码 1.1、在自己的小程序中创建组件 1.2、组件…

import是如何“占领满屏“

import是如何“占领满屏“的&#xff1f; 《拒绝使用模块重导&#xff08;Re-export&#xff09;》 模块重导是一种通用的技术。在腾讯、字节、阿里等各大厂的组件库中都有大量使用。 如&#xff1a;字节的arco-design组件库中的组件&#xff1a;github.com/arco-design… …

鸿蒙分享(二):引入zrouter路由跳转+封装

码仓库&#xff1a;https://gitee.com/linguanzhong/share_harmonyos 鸿蒙api:12 鸿蒙第三方库地址&#xff1a;OpenHarmony三方库中心仓 zrouter地址&#xff1a;OpenHarmony三方库中心仓 1.引入zrouter 1.打开终端界面&#xff1a;输入 ohpm install hzw/zrouter 2.在项目…

第七节(2)、T型加减速优化处理【51单片机-TB6600驱动器-步进电机教程】

摘要&#xff1a;本节介绍解决标准T型加减速过程中的两个缺陷&#xff0c;其一是使得初速度任意设置&#xff1b;其二是降低Cn递推计算量&#xff0c;提升速度上限 一. 加速减速过程计算 1.1计算不存在匀速过程 根据基本运动定理&#xff1a; w m a x w 0 a 0 ∗ t n 0 … …

MySQL--用户权限

1.使用root用户登录MySQL客户端&#xff0c;创建一个名为userl的用户&#xff0c;初始密码为123456;创建一个名为user2的用户&#xff0c;无初始密码。然后&#xff0c;分别使用uesr1、user2登录MySQL 客户端。 创建两个用户 使用user1登录 使用user2登录 2.使用root用户登录&a…

最新版Chrome谷歌加载ActiveX控件之金格iWebOffice2015控件

allWebPlugin简介 allWebPlugin中间件是一款为用户提供安全、可靠、便捷的浏览器插件服务的中间件产品&#xff0c;致力于将浏览器插件重新应用到所有浏览器。它将现有ActiveX控件直接嵌入浏览器&#xff0c;实现插件加载、界面显示、接口调用、事件回调等。支持Chrome、Firefo…

实现跨平台 SSH 连接:从 macOS 到 Windows WSL 的完整解决方案20241203

&#x1f310; 实现跨平台 SSH 连接&#xff1a;从 macOS 到 Windows WSL 的完整解决方案 ✨ 引言 随着跨平台开发的普及&#xff0c;开发者经常需要在多系统环境中切换和协作。尤其是在 macOS 和 Windows 混合使用的开发环境中&#xff0c;通过 SSH 远程访问和管理 Windows …

C语言——习题练习(一)

习题&#xff1a; 现在有两种面值的邮票&#xff0c;一种为8角&#xff0c;一种为6角。你要付n角的邮资&#xff08;不能多付也不能少付&#xff09;&#xff0c;请给出邮票张数最少的方案。如果没有正好的方案则输出-1。 输入格式: 只有一行&#xff0c;为若干个整数&#xf…

Redis 数据结结构(一)—字符串、哈希表、列表

Redis&#xff08;版本7.0&#xff09;的数据结构主要包括字符串&#xff08;String&#xff09;、哈希表&#xff08;Hash&#xff09;、列表&#xff08;List&#xff09;、集合&#xff08;Set&#xff09;、有序集合&#xff08;Sorted Set&#xff09;、超日志&#xff08…

短视频矩阵系统saas源码 ---技术源头搭建部署

短视频矩阵系统源码 短视频矩阵系统源码主要有三种框架&#xff1a;Spring、Struts和Hibernate。Spring框架是一个全栈式的Java应用程序开发框架&#xff0c;提供了IOC容器、AOP、事务管理等功能。Struts框架是一个MVC架构的Web应用程序框架&#xff0c;用于将数据模型、Web应用…

李飞飞:Agent AI 多模态交互的前沿探索

发布于:2024 年 11 月 27 日 星期三 北京 #RAG #李飞飞 #Agent #多模态 #大模型 Agent AI在多模态交互方面展现出巨大潜力,通过整合各类技术,在游戏、机器人、医疗等领域广泛应用。如游戏中优化NPC行为,机器人领域实现多模态操作等。然而,其面临数据隐私、偏见、可解释性…