svg在vue中的使用配置和vue中定义mixins混入

210 阅读1分钟

svg想在vue中使用是必要的要进行配置的

首先在vue.config.js中进行配置
下完包之后
chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    // 清除已有的所有 loader。
    // 如果你不这样做,接下来的 loader 会附加在该规则现有的 loader 之后。
    svgRule.uses.clear()
    svgRule
      .test(/\.svg$/)
      .include.add(path.resolve(__dirname, './src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
    const fileRule = config.module.rule('file')
    fileRule.uses.clear()
    fileRule
      .test(/\.svg$/)
      .exclude.add(path.resolve(__dirname, './src/assets/icons'))
      .end()
      .use('file-loader')
      .loader('file-loader')
  }
然后在assets里面新建icons文件夹里面放入下载下来的svg图标再新建一个index.js文件为他统一全部注册了
import Vue from 'vue'
import SvgIcon from '../../components/svgIcon'// svg component

// register globally
Vue.component('svg-icon', SvgIcon)
/**
 * 引入的是assets下面的icons
 */
// eslint-disable-next-line
const req = require.context('../icons', false, /\.svg$/)
// eslint-disable-next-line
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
然后新建一个公共的组件方便维护和复用
<template>
  <svg class="svg-icon" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
<script>
export default {
  name: 'icon-svg',
  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 lang="scss" scoped>
  .svg-icon {
    /**width: 1em;
    height: 1em;**///根据自己需要来
    width: 100%;
    height: 100%;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
</style>

最后 main.js中引入
import './assets/icons/index.js'
最后使用的时候这样直接使用就可以
<svg-icon icon-class="a" />
clss的类名就是svg图标的名字

vue中的mixins混入当多个组件用到一个逻辑的时候需要进行混入

首先新建mixins文件夹,然后新建一个js文件
mixins混入其实就和正常的一模一样,生命周期,事件等等只不过是把他搬过来的而已
比如下面的这个scroll是事件的绑定
export default {
  mounted () {
    this._initScrollEvent()
    console.log('2')
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this._scrollEvent)
  },
  methods: {
    _initScrollEvent () {
      window.addEventListener('scroll', this._scrollEvent)
    },
    _scrollEvent (e) {
      const scrollY = window.scrollY
      const viewHeight = window.innerHeight
      const bodyHeight = document.body.clientHeight - 1
      if (scrollY + viewHeight > bodyHeight) {
        this.scrollBottom()
      }
    }
  }
}

// mixins混入引入 mixins: [scrollBottom],引入的文件名称 mixins里面之地那个事件直接写到metheds里面就可以 他们会直接结合起来 scrollBottom () { this.featchParams.page += 1 this.fatchProduct() console.log('1') }