
vue3 elementplus el-Icon 动态渲染 点击切换icon图标组件
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element

·
记录一下在项目中碰到的问题,很简单的一个效果,点击小眼睛切换密码显示状态,但是查了好久资料没查到怎么用el-icon实现,样式怎么调,遂记录一下。
目标效果:
实现原理
首先安装Element Plus提供的图标集合
使用包管理器
# 选择一个你喜欢的包管理器
# NPM
$ npm install @element-plus/icons-vue
# Yarn
$ yarn add @element-plus/icons-vue
# pnpm
$ pnpm install @element-plus/icons-vue
注册所有图标
// main.ts
// 如果您正在使用CDN引入,请删除下面一行。
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
也可以看看官方文档,Element Plus Icon 图标
但是官方文档太精简,很多用法还是得自己查,就比如我想实现这个点击切换两个icon图标的方式,
这里用了动态组件component标签,具体渲染哪个组件由点击事件切换is的值,
<component class="password-icon" :is="showPassword ? 'View' : 'Hide'" @click="toggleShowPassword"/>
如果想增加额外的样式可以用el-icon
包裹component
<el-icon size="66" color="lightblue">
<component class="password-icon" :is="showPassword ? 'View' : 'Hide'" @click="toggleShowPassword"/>
</el-icon>
在Elementplus中可以直接用<Edit />
<View />
等组件名来表示icon图标
这样就达成了直接用图标组件名字调用图标的效果。
具名插槽
<template #default="{ row }">
<span v-if="showPassword">{{ row.password }}</span>
<span v-else>******</span>
</template>
调样式也是调了半天,毕竟elementplus组件日常受全局默认样式影响,scope里面必要可能需要:deep
或者!important
进行样式覆盖,笔者是菜鸟,只能慢慢试错;
先用一个div把span和component包起来实现居中,再给组件标签一个class来调整icon的大小边距等。
代码部分
部分代码没贴,数据是从后端拿的
template部分
<template>
<div class="userManage">
<div class="user_show">
<el-table :data="tableData" style="width: 55%" :header-cell-style="{ color: '#efefef', background: '#1d0daf' }"
row-class-name="table_row">
<el-table-column prop="user" label="用户名" />
<el-table-column prop="password" label="密码">
<template #header>
<div class="password-header">
<span>密码</span>
<component class="password-icon" :is="showPassword ? 'View' : 'Hide'" @click="toggleShowPassword" />
</div>
</template>
<template #default="{ row }">
<span v-if="showPassword">{{ row.password }}</span>
<span v-else>******</span>
</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
js部分
<script lang="ts" setup>
import { ref } from 'vue'
const tableData = ref([])
const showPassword = ref(false)
const toggleShowPassword = () => {
showPassword.value = !showPassword.value; // 切换密码显示状态
};
</script>
css部分
<style lang="less" scoped>
.userManage {
padding: 2px 50px;
height: 100px;
.user_show {
display: flex;
justify-content: center;
.password-header {
display: flex;
align-items: center;
/* 垂直居中对齐 */
justify-content: center;
/* 水平居中对齐 */
}
.password-icon {
margin-left: 8px;
width: 20px;
}
}
}
:deep(.el-table) {
.cell {
text-align: center;
/* 单元格内容居中 */
}
}
</style>
有问题欢迎交流学习




A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:8 个月前 )
c345bb45
1 年前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 1 年前
更多推荐
所有评论(0)