解决内外部svg图标方案 + 遇到的奇怪的bug

vue: 3.2.8 webpack: 4.46.0

浏览器错误:

[Vue warn]: Extraneous non-props attributes (class) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. at <Index class="hamburger" icon="hamburger-opened" > at <Index class="hamburger-container" > at <Navbar> at <Index onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > at <RouterView> at <App

vue代码:解决内外部svg图标方案

<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.js'
import { computed, defineProps } from 'vue'
const props = defineProps({
  // incon图标
  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 lang="scss" 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;
}
</style>

解决方案:

去掉html中的注释代码(展示内部图标 展示外部图标),问题即解决。

猜你喜欢

转载自blog.csdn.net/DoubleLift_DSX/article/details/122117748