美文网首页
Vue2.0 中玩转svg

Vue2.0 中玩转svg

作者: Luoyilin | 来源:发表于2019-12-13 19:02 被阅读0次
svg 图标资源哪里来?

阿里巴巴开源的iconfont上找

image.png
言归正传 如下是具体步骤:
1.下载安装svg-sprite-loader插件
    npm install svg-sprite-loader --save-dev  // ---> 一定要加-dev 不然图标不显示 反正我在这里踩了半天坑 具体原因不清楚 猜想是和 后面文件的配置路径有关系  

2.新建文件目录
01).在src 目录下 新建icons文件夹 在Icons目录下新建svg文件夹 和index.js 文件

image.png
02). index.js 中的配置代码如下 :
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // svg组件
// 注册到全局
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

03).在src目录下 components 新建 Svgicon.vue 通用组件 添加配置代码如下:

<template>
  <svg :class="svgClass" aria-hidden="true" :width="swidth" :height="sheight">
    <use :xlink:href="iconName" />
  </svg>
</template>
<script>
export default {
  name: "SvgIcon",
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ""
    },
    size: {
      type: [String, Number],
      default: 20
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return "svg-icon " + this.className;
      } else {
        return "svg-icon";
      }
    },
    swidth() {
      if (this.size < 0 || isNaN(this.size)) {
        return 20;
      }
      return this.size;
    },
    sheight() {
      if (this.size < 0 || isNaN(this.size)) {
        return 20;
      }
      return this.size;
    }
  }
};
</script>

<style scoped>
.svg-icon {
  /* width: 1em; 自定义 图标的大小
  height: 1em; */
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

04).在src目录下 main.js 中添加配置代码如下:

import '@/icons'   

项目中的代码已经完成_
接下来 要进行对webpack 中的 webpack.base.conf.js添加相关配置规则

module:{
       //.... module 中其他本身的配置此处进行了省略
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')], // --->新添加
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
       {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        options: {
          symbolId: 'icon-[name]'
        },
        include: [resolve('src/icons')] // 把上面去掉的文件夹include进来
      },

  }

如何使用(在使用之前需从iconfont网站里面下载好svg文件,例如下载一个svg-.svg的文件,放在src/icons/svg文件夹里面)
在需要使用svg组件的地方 添加 如下代码:

<svg-icon   icon-class = "svg-" size="40"></svg-icon>
<svg-icon   icon-class = "svg" size="40"></svg-icon>
<svg-icon   icon-class = "svginvitation" size="40"></svg-icon>
image.png

实现效果如下 :


image.png

相关文章

网友评论

      本文标题:Vue2.0 中玩转svg

      本文链接:https://www.haomeiwen.com/subject/phhqnctx.html