如何在vue_cli里面使用svg
时间: 2023-12-30 22:02:42 浏览: 33
在 Vue CLI 中使用 SVG 可以通过以下步骤实现:
1. 安装依赖: `npm install vue-svg-loader svg-inline-loader -D`
2. 在 `vue.config.js` 文件中添加以下配置:
```javascript
module.exports = {
chainWebpack: config => {
const svgRule = config.module.rule("svg");
// 清除已有的所有 loader。
// 如果你只是想添加一个 loader,可以使用 `unshift` 方法。
svgRule.uses.clear();
// 添加要替换的 loader
svgRule
.use("vue-svg-loader")
.loader("vue-svg-loader")
.end()
.use("svg-inline-loader")
.loader("svg-inline-loader")
.end();
}
};
```
3. 在组件中使用 SVG:
```vue
<template>
<div>
<svg-icon name="example" />
</div>
</template>
<script>
export default {
components: {
SvgIcon: () => import("@/components/SvgIcon.vue")
}
};
</script>
```
在 `@/components/SvgIcon.vue` 文件中,可以定义一个 `props` 接收 `name`,然后使用 `require` 导入对应的 SVG 图标,并使用 `v-html` 渲染到页面上:
```vue
<template>
<div v-html="icon"></div>
</template>
<script>
export default {
props: {
name: {
type: String,
required: true
}
},
computed: {
icon() {
return require(`@/assets/svg/${this.name}.svg`);
}
}
};
</script>
```
注意:以上代码仅供参考,具体实现可能因具体项目而异。