vue中封裝svg-icon組件並使用

vue中使用svg圖片有不少便捷方式,在這裏記錄一下模仿參考的過程,僅作一標記,方便後續回來查找

附上參考地址:https://juejin.im/post/59bb864b5188257e7a427c09html

1.使用vue-cli3.0腳手架運行搭建一個項目,地址vue

截圖以下:vue-cli

2.components文件下新建SvgIcon組件ide

文件中的代碼以下:svg

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

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>

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

3.將所需svg文件放置icons的svg文件夾下post

icons文件下的index.js文件中的代碼以下:ui

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件

// register globally
Vue.component('svg-icon', SvgIcon)

const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

4.main.js中引入icons文件this

5.直接在組件中使用icon-class爲svg名字的圖標便可spa

6.注意:安裝svg-sprite-loader,而且在vue.config.js文件下配置3d

7.運行項目,顯示圖標

相關文章
相關標籤/搜索