vue中使用svg-icon

    之前也写过一篇这样的文章,只需要配置在线地址,即可自动下载几个字体文件,但是呢,我发现还有一种更好的写法,也是大众化的写法,即 svg标签,参考如何优雅的使用icon,可以完全参考这篇进行开发。

    我就是记录一下如何使用

1 在src目录新建一个icons目录,目录结构如下

svg下面放iconfont的icon标签的svg标签文件,下下来复制粘贴即可使用

index.js文件:

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

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

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

如上面代码而言,我们需要封装一下icon,在components下新建SvgIcon文件

index.vue文件内容:

<template>
  <svg :class="svgClass" aria-hidden="true">
    <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>

当然如参考文章所言,我们须加载依赖svg-sprite-loader,在webpack.base.conf.js 中

具体为什么这么用,请参考优雅的使用icon。

因为组件已经全局注册,即在组件中   <svg-icon iconClass="money"></svg-icon>  使用即可,这种用法好处很多。具体参考 你懂的。我就简单记录一下copy代码的过程而已。

猜你喜欢

转载自blog.csdn.net/shentibeitaokong/article/details/83039021
今日推荐