如何在vue中使用iconify组件
参考链接:图标 | FastCrud
- 安装依赖
//package.json
{
"dependencies": {
"@iconify/iconify": "^3.0.1",
}
"devDependencies": {
"unplugin-icons": "^0.15.1",
}
}
- 配置Vite插件
// vite.config.js
import Icons from 'unplugin-icons/vite'
return {
plugins: [
vue(),
Icons({compiler: 'vue3', autoInstall: true}) // 主要配置它
]
}
- 创建icon组件,并注册成全局组件
// icon.vue
<template>
<span ref="iconifyRef" :class="[$attrs.class, 'my-iconify']" :style="getIconifyStyle"></span>
</template>
<script setup lang="ts">
import {computed, nextTick, onMounted, ref, unref, watch} from "vue";
import {propTypes} from '@/utils/propTypes'
import Iconify from "@iconify/iconify/dist/iconify";
const props = defineProps({
icon: propTypes.string,
color: propTypes.string,
size: propTypes.number.def(0.2)
})
const iconifyRef = ref<ElRef>(null)
const getIconifyStyle = computed(() => {
const {color, size} = props
return {
fontSize: `${size}rem`,
display: "inline-flex",
color
}
})
const updateIcons = async () => {
if (!props.icon) return;
const el = unref(iconifyRef);
if (!el) return;
await nextTick();
const svg = Iconify.renderSVG(props.icon, {})
if (svg) {
el.textContent = '';
el.appendChild(svg);
} else {
const span = document.createElement('span');
span.className = 'iconify';
span.dataset.icon = props.icon;
el.textContent = '';
el.appendChild(span);
}
}
onMounted(() => updateIcons())
</script>
import type {App} from 'vue'
import {Icon} from './icon'
// 全局组件
export const setupGlobCom = (app: App<Element>): void => {
app.component('Icon', Icon)
}
- 选择图标
官网地址:Icon Sets • Iconify
- 使用
<Icon icon="ion:skull" color="red" size="0.2"/>