在Vue项目中,可以通过以下步骤引入svg图片:

  1. 在项目中创建一个svg文件夹,将需要使用的svg图片放入其中。

  2. vue.config.js中添加svg-sprite-loader配置:

const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')

    svgRule.uses.clear()

    svgRule
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
        include: [resolve('src/icons')]
      })
  }
}

这里使用了svg-sprite-loader,它会将所有的svg图片打包成一个svg sprite,方便在项目中使用。

  1. 在需要使用svg图片的组件中,通过以下方式引入:
<template>
  <div>
    <svg>
      <use xlink:href="#icon-xxx"></use>
    </svg>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  // ...
}
</script>

这里的#icon-xxx中的xxx是svg图片的文件名,通过symbolId配置可以设置前缀。

这样就可以在Vue项目中方便地使用svg图片了

如何在vue项目中通过文件引入svg图片给出代码及解释

原文地址: https://www.cveoy.top/t/topic/ckXY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录