手把手带你撸nuxtjs(四)--使用svg 和icon

其实此功能为element-vue-admin 上面扒拉下来的!不过需要根据nuxt来修改下!

1、plugins文件夹下新建 icons.js

import Vue from 'vue'
// 引用组件
import SvgIcon from '@/components/SvgIcon.vue'

// 注册全局组件,组建名为svg-icon
Vue.component('svg-icon', SvgIcon)

// 引用svg图标
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('@/assets/icons/svg', true, /\.svg$/)
requireAll(req)

2、新建assets>icons>svg目录,里面随便放个svg图片把!

3、下载依赖

npm install svg-sprite-loader --save-dev

4、修改nuxt.config.js文件,

在最上面添加

const path = require('path')

然后找找到build,添加

 build: {
    extend (config, ctx) {
      // ...
      const svgRule = config.module.rules.find(rule => rule.test.test('.svg'))
      svgRule.exclude = [path.resolve(__dirname, 'assets/icons/svg')]
      // Includes /icons/svg for svg-sprite-loader
      config.module.rules.push({
        test: /\.svg$/,
        include: [path.resolve(__dirname, 'assets/icons/svg')],
        loader: 'svg-sprite-loader',
        options: {
          symbolId: 'icon-[name]'
        }
      })
    }
  }

5、在components内添加组件SvgIcon.vue

<template>
  <div
    v-if="isExternal"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    v-on="$listeners"
  />
  <svg
    v-else
    :class="svgClass"
    aria-hidden="true"
    v-on="$listeners"
  >
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
 function isExternal (path) {
    return /^(https?:|mailto:|tel:)/.test(path)
  }


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

<style 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;
  display: inline-block;
}
</style>

6、使用 password为你svg文件得名字

  <svg-icon icon-class="password" />

效果

image.png

相关内容

发表评论

验证码:
点击我更换图片

最新评论