在 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/ntJZ 著作权归作者所有。请勿转载和采集!

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