參考 Vue項目中使用svg圖標 這篇軟文質量不錯, 依葫蘆畫瓢,也跑通了
1.慢慢在理解其中包含的知識
2. 把自己理解換一種方式表達一下
我們想在vue頁面使用svg圖標,例如
<template> <div> <h1>Svg實踐,在頁面中使用</h1> <svg-icon icon-class="add"></svg-icon> <svg-icon icon-class="auto"></svg-icon> </div> </template> <script> export default { props: {}, components: {}, data() { return {}; }, computed: {}, created() {}, mounted() {}, watch: {}, methods: {} }; </script>
參考上面的文章
以上代碼是svg的原生用法(正確性未驗證)
1. src/icons 目錄, 導入 svg 資源文件
2. npm install svg-sprite-loader --save-dev =>package.json
3. 配置webpack.base.conf.js(build文件夾中)
//設置Webpack 用 svg-sprite-loader 加載, src/icons 目錄的內容,
換一種方式:
1). 在 rules 下增加
{ test: /\.svg$/, loader: "svg-sprite-loader", include: [resolve("src/icons")], options: { symbolId: "icon-[name]" } },
//實際效果是,上面配置后webpack會加載src/icons下的index.js
2). webpack.base.conf.js 原生的 loader: 'url-loader',中去掉svg,就不再額外添加
指令: exclude:[resolve('src/icons')] ,
如下:
{ test: /\.(png|jpe?g|gif)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } },
4. 自定義svg組件封裝svg功能
基礎核心知識
src\icons\index.js 中
import SvgIcon from '@/components/SvgIcon' 的加載行為
加載 src\components\SvgIcon\index.vue
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
在Vue中使用svg圖標即封裝自定義svg-icon標簽
如在 SvgDemo.vue 使用如下標簽
<template> <div> <h1>Svg實踐,在頁面中使用</h1> <svg-icon icon-class="add"></svg-icon> <svg-icon icon-class="auto"></svg-icon> </div> </template>