封裝svg通用組件

vue版本2.6.14
目錄如下


image.png

package.json

// devDependencies中安裝開(kāi)發(fā)依賴(lài)
"svg-sprite-loader": "^6.0.11",

vue.config.js

const { defineConfig } = require('@vue/cli-service')

const path = require('path');
function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = defineConfig({
  devServer: {
    open: true,
    host: 'localhost',
    port: 8080
  },
  transpileDependencies: true,
  lintOnSave: false,
  chainWebpack: config => {
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/svg'))
      .end();
    config.module
      .rule('svgs-loader')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();
}
})

SvgIcon.vue

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>

export default {
  name: 'SvgIcon',
  props: {
    // svg圖標(biāo)名稱(chēng)
    iconClass: {
      default: ''
    },
    // 自定義樣式
    className: {
      type: String,
      default: ''
    },
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      return [
        'svg-icon',
        this.className ? this.className:''
      ]
    }
  }
};
</script>

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

svg-icon/index.js

import SvgIcon from './SvgIcon.vue'
export default (Vue) => {
  // 全局注冊(cè)
  Vue.component('svg-icon', SvgIcon);
  // 導(dǎo)入所有svg文件
  const requireAll = requireContext => requireContext.keys().map(requireContext);
  const req = require.context('@/assets/svg', false, /\.svg$/);
  requireAll(req);
}

index

import SvgIcon from "./svg-icon";
export default (Vue) => {
  Vue.use(SvgIcon);
}

main.js

// 增加
import PublicComponent from '@/components'
Vue.use(PublicComponent);

使用組件

<svg-icon icon-class="add" class="svg-color"/>

<style scoped>
.svg-color {
  color: red;
}
</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容