【搭建/全套解决方案/部署】vue3的后台管理系统-07-Icon 图标处理方案1:外部图标

185 阅读1分钟

图标处理方案1:外部图标

创建 components/SvgIcon/index.vue

使用了引用组件的技术

是一个解决方案,复制就是

<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    :class="className"
  />
  <svg v-else class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup>
import { isExternal as external } from '@/utils/validate'
import { defineProps, computed } from 'vue'
const props = defineProps({
  // icon 图标
  icon: {
    type: String,
    required: true
  },
  // 图标类名
  className: {
    type: String,
    default: ''
  }
})

/**
 * 判断是否为外部图标
 */
const isExternal = computed(() => external(props.icon))
/**
 * 外部图标样式
 */
const styleExternalIcon = computed(() => ({
  mask: `url(${props.icon}) no-repeat 50% 50%`,
  '-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))
/**
 * 项目内图标
 */
const iconName = computed(() => `#icon-${props.icon}`)
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

创建 utils/validate.js

用于判断的工具


/**
 * 判断是否为外部资源
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

views/login/index.vue 中使用 外部 svghttps://res.lgdsunday.club/user.svg):

import SvgIcon from '@/components/SvgIcon/index.vue'

//这个放在输入框那个地方
<span class="svg-container">
	<svg-icon icon="https://res.lgdsunday.club/user.svg"></svg-icon>
</span>

因为你给文件名起index.vue,就会报错,所以可以:

找到名为 ".eslintrc.js" 或 ".eslintrc.json" 的文件,打开它并找到 "rules" 字段。

在 "rules" 字段中,你可以添加一个新的规则来屏蔽这个错误。将以下代码添加到规则列表中:

 'vue/multi-word-component-names': 'off'

引入外部组件成功 image.png