Element-plus的引入和部分组件的使用

Element-plus

1. 按需导入

  • 安装element
npm install element-plus --save
pnpm add element-plus
  • 按需引入
npm install -D unplugin-vue-components unplugin-auto-import
pnpm add -D unplugin-vue-components unplugin-auto-import
  • 修改vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    })
  ],

这里的按需引入的两个插件,并不是只为element服务的,它也可以自动引入其他内容

    // 自动导入api
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: ['vue', 'pinia', 'vue-router'],	// 引入这些文件中的api,以后就不用写import {ref} from 'vue'了
      dts: 'src/auto-imports.d.ts', // 生成自动导入的类型声明文件
    }),
    // 自动导入组件
    Components({
      resolvers: [ElementPlusResolver()],
      dirs: ['src/components', 'src/layout/components'], // 自动导入这些文件夹中定义的组件
    }),

至此按需引入element就可以使用了

1. 使用自动导入后Eslint报错

解决办法

2. 组件上面悬停提示

  • 在tsconfig.app.json文件中加入:"types": ["element-plus/global"]
  • 把鼠标悬停在element的标签上就能有提示了,感觉看到提示也没有啥用
    在这里插入图片描述

2. 按需导入后部分插件不可用的解决办法

  • 按需导入后Element,使用ElMessageLoading时,屏幕并没有显示,这是因为按需导入时没有导入ElMessageLoading样式

1. 手动引入样式

  1. main.ts中导入Element的全部样式import 'element-plus/dist/index.css',但是这样违背了当初按需导入的初衷
  2. 只导入ElMessage的样式,import 'element-plus/theme-chalk/el-message.css

2. 使用插件自动引入

  • 安装插件
    • vite-plugin-style-import依赖于consola
pnpm add -D vite-plugin-style-import consola
  • 修改vite.config.ts
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'

export default defineConfig({
  plugins: [
    vue(),
    createStyleImportPlugin({
    // 在nodel-module文件夹中找到element组件的css并引入
      resolves: [ElementPlusResolve()],
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          resolveStyle: (name) => {
            return `element-plus//theme-chalk/${name}.css`
          }
        }
      ]
    })
  ],
  ...
})

3. 安装插件(官网的方法)

pnpm add -D unplugin-element-plus
  • vite.config.ts
import { defineConfig } from 'vite'
import ElementPlus from 'unplugin-element-plus/vite'

export default defineConfig({
  // ...
  plugins: [ElementPlus({})],
})

3. 动态菜单实现权限管理

  • 服务器返回的真实数据
 [
    {	// 一级菜单数组
       "id": 38,
       "name": "系统总览",
       "type": 1,
       "url": "/main/analysis",
       "icon": "el-icon-monitor",
       "sort": 1,
       "children": [	// 二级菜单数组
           {
               "id": 39,
               "url": "/main/analysis/overview",
               "name": "核心技术",
               "sort": 106,
               "type": 2,
               "children": null,
               "parentId": 38
           },
           {
               "id": 40,
               "url": "/main/analysis/dashboard",
               "name": "商品统计",
               "sort": 107,
               "type": 2,
               "children": null,
               "parentId": 38
           }
       ]
    }
 ]
  • 菜单目录
<template>
    <el-menu
      active-text-color="#fff"
      text-color="#b7bdc3"
      background-color="#001529"
    >
    <!-- 循环遍历一级菜单 -->
      <template v-for="item in roleMenu" :key="item.id">
        <el-sub-menu :index="item.url">
          <template #title>
          	 <!-- 一级菜单的图标 -->
            <el-icon>
              <component :is="item.icon.split('el-icon-')[1]" />
            </el-icon>
            <span>{{ item.name }}</span>
          </template>
          <!-- 循环遍历二级菜单 -->
          <template v-for="cItem in item.children" :key="cItem.id">
            <el-menu-item :index="cItem.url">{{ cItem.name }}</el-menu-item>
          </template>
        </el-sub-menu>
      </template>
    </el-menu>
  </div>
</template>
  • 注意:
    1. index中的路径必须以/开头
    2. 当点击菜单项时会导航到<el-menu-item>index的路径,并且这个路径是绝对路径,它不会拼接上一级 <el-sub-menu :index="item.url">index的路径
  • html的解释
    • active-text-color:活动菜单项的文本颜色
    • text-color:菜单的文字颜色
    • background-color:菜单的背景颜色
    • roleMenu:服务器返回的菜单数据
    • <component :is="item.icon.split('el-icon-')[1]" />:服务器返回的图标的字符串为 el-icon-chat-line-round 字符串切割后使用chat-line-round部分,生成 html 代码<el-icon><chat-line-round></el-icon>
    • :index="item.id + ''"index 的值必须为 string,把 number 变为字符串
  • 菜单中的各级
    • el-menu:整个菜单,背景色,文字颜色
    • el-sub-menu: 一级菜单,背景色,激活时颜色(二级菜单激活自动激活一级)
    • el-menu-item:二级菜单,背景色,鼠标悬停颜色,激活时颜色
// 菜单的style
.el-menu {	// 整个菜单
  height: 100%;
  // --el-menu-border-color: #001529; // menu右边框的颜色设置与底同色也能隐藏这1px的border
  border-right: none; // menu有个1px的右边框,设置为空
  .el-sub-menu {	// 一级菜单,无法点击
    .el-menu-item {		// 设置二级菜单的样式
      padding-left: 60px;	
      background-color: #0c2135; // 菜单项的背景色
    }
    .el-menu-item:hover {
      background-color: #0a60bd;
      color: #fff; // 鼠标悬停时的颜色
    }
    .el-menu-item.is-active {
      background-color: #0a60bd; // 被选中的菜单的背景颜色
    }
  }
}
  • 布局中的左侧aside
    .el-aside {
      // height: 100%;
      background-color: #001529;
      // overflow-x: hidden;
      // overflow-y: auto;
      // text-align: left;
      // cursor: pointer;
      // transition: width 0.3s linear;
      // scrollbar-width: none;
      &::-webkit-scrollbar {
        display: none;	// 最主要的,去除滚动条
      }
    }
  • 效果
    在这里插入图片描述

4. 下拉菜单在focus时总有个黑框

  1. 方法1:
.el-tooltip__trigger {
  outline: none;
}
  1. 方法2:
    其他方法链接

5. 表单校验

rules: 数据验证
model和prop的值是由与定义的响应式变量名对应
在这里插入图片描述

在这里插入图片描述

6 <el-image>使用本地图片

Vue3+TypeScript+Vite如何使用require动态引入类似于图片等静态资源

<el-image :src="url"/>

const url = new URL(
    '../images/dataScreen-header-btn-bg-r.png', // 本地图片的路径
    import.meta.url,
).href

7. 主题相关

  1. 设置自定义主题
    创建scss文件
@forward "element-plus/theme-chalk/src/common/var.scss" with (
  $colors: (
    "primary": ("base": #2c82ff),
    "success": ("base": #31bf00),
    "warning": ("base": #ffad00),
    "danger": ("base": #e52f2f),
    "info": ("base": #8055ff),
  )
);
  1. 在vite.config中配置
  • 预加载scss文件
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/assets/css/index.scss" as *;`
      }
    }

有两种方式可以使scss文件生效
①官网的方法

plugins: [
    vue(),
    ElementPlus({useSource: true,}),	
]

②自动引入中添加

  • 这种方法只有在完整引入element时生效
    Components({
      resolvers: [ElementPlusResolver({importStyle:"sass"})]
      // dirs: ['src/components', 'src/layout/components'],
    })

8. 面包屑

  • 基本通用,保证路由的metatitle属性有值
<template>
  <div class="breadcrumb">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <template v-for="(item, index) in pathname" :key="index">
        <template v-if="item.path != '/' && item.title != ''">
          <el-breadcrumb-item :to="{ path: item.path }">{{ item.title }}</el-breadcrumb-item>
        </template>
      </template>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { computed } from 'vue'
const route = useRoute()

const pathname = computed(() => {
  return route.matched
    .filter((item) => item.meta?.title) // 过滤掉没有title的路由信息
    .map((item) => ({
      title: item.meta.title || '',
      path: item.path,
      icon: item.meta?.icon || '',
    }))
})
</script>

<style scoped lang="scss">
:deep(.el-breadcrumb) {
  font-size: 18px;
}
</style>

9. KeepAlive & Transition

<template>
  <div class="content">
    <router-view v-slot="{ Component }">
      <Transition name="fade" mode="out-in">
        <KeepAlive>
          <component :is="Component"></component>
        </KeepAlive>
      </Transition>
    </router-view>
    <!-- <router-view /> -->
  </div>
</template>

<script setup lang="ts"></script>

<style scoped lang="scss">
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
### 如何在 `vue-element-plus-admin` 项目中引入使用 Element Plus 组件 #### 安装依赖包 为了能够顺利使用 Element Plus组件,在项目的根目录下执行如下命令来安装必要的依赖: ```bash npm install element-plus @types/element-plus --save ``` 这一步骤确保了所有必需的库都已就绪并可以被导入到应用程序之中[^2]。 #### 配置按需加载 (Optional) 如果希望减少打包体积,可以选择只引入所需的组件而不是整个库。通过借助插件如 `unplugin-vue-components` `unplugin-auto-import` 可实现这一点。首先需要安装这些工具: ```bash npm install unplugin-vue-components unplugin-auto-import -D ``` 接着修改 vite.config.ts 文件配置上述两个插件: ```typescript import { defineConfig } from 'vite' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' export default defineConfig({ plugins: [ AutoImport({ imports: ['vue', 'vue-router', '@vueuse/core'], dts: true, }), Components({ resolvers: [ // 自动注册来自 Element Plus组件 { type: 'component', resolve: name => ({ name, from: 'element-plus' }) } ] }) ], }) ``` 这样设置之后就可以自动解析并按需加载 Element Plus 组件而无需手动一一声明。 #### 使用单个组件实例 当只需要在一个页面或模块里单独使用某个特定组件时可以直接从 `element-plus` 导入它,并将其添加至当前文件内的 components 属性列表内: ```html <template> <el-button>默认按钮</el-button> </template> <script lang="ts"> import { ElButton } from "element-plus"; // 或者 ES6 解构赋值方式 import { Button as ElButton } from 'element-plus'; export default { name: "ExampleComponent", components: { ElButton }, }; </script> ``` 此方法适用于那些不经常使用的特殊场景下的控件,因为它允许更细粒度地控制哪些部分应该被打包进来[^1]。 #### 全局注册全部组件 对于大多数情况下推荐的方式是在 main.ts 中全局注册所有的 Element Plus 组件以便在整个应用范围内随时调用它们: ```typescript import { createApp } from 'vue'; import App from './App.vue'; import * as ElementPlus from 'element-plus'; const app = createApp(App); app.use(ElementPlus); app.mount('#app'); ``` 这种方式简化了开发流程因为不再需要每次都要显式指定要使用的具体组件名称;但是请注意这样做可能会增加最终构建产物大小所以仅当你确实需要用到很多不同类型的 UI 控制器才考虑采用这种方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值