vue3.0 + svg 圖示
阿新 • • 發佈:2021-06-15
1、安裝svg:
npm install svg-sprite-loader --save-dev
2、在components 中,建立 SvgIcon,引入 svg 樣式:
index.vue:
<template> <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName" aria-hidden="true" /> </svg> </template> <script> import { defineComponent, computed }from "vue"; export default defineComponent({ name: "svg-icon", props: { iconClass: { type: String, required: true }, className: { type: String, default: "" } }, setup(props) { console.log(props.iconClass);const iconName = computed(() => `#icon-${props.iconClass}`); const svgClass = computed(() => { if (props.className) { return "svg-icon " + props.className; } else { return "svg-icon"; } });return { iconName, svgClass }; } }); </script> <style scoped> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
3、src 新建 icons:
svgo.yml:
# replace default config # multipass: true # full: true plugins: # - name # # or: # - name: false # - name: true # # or: # - name: # param1: 1 # param2: 2 - removeAttrs: attrs: - 'fill' - 'fill-rule'
svg 在阿里向量圖下載
例如:在 src/icons/svg 下,新建 .svg 檔案,複製 svg 程式碼,
https://www.iconfont.cn/search/index?searchType=icon&q=眼睛
eye.svg:
<svg width="128" height="64" xmlns="http://www.w3.org/2000/svg"><path d="M127.072 7.994c1.37-2.208.914-5.152-.914-6.87-2.056-1.717-4.797-1.226-6.396.982-.229.245-25.586 32.382-55.74 32.382-29.24 0-55.74-32.382-55.968-32.627-1.6-1.963-4.57-2.208-6.397-.49C-.17 3.086-.399 6.275 1.2 8.238c.457.736 5.94 7.36 14.62 14.72L4.17 35.96c-1.828 1.963-1.6 5.152.228 6.87.457.98 1.6 1.471 2.742 1.471s2.284-.49 3.198-1.472l12.564-13.983c5.94 4.416 13.021 8.587 20.788 11.53l-4.797 17.418c-.685 2.699.686 5.397 3.198 6.133h1.37c2.057 0 3.884-1.472 4.341-3.68L52.6 42.83c3.655.736 7.538 1.227 11.422 1.227 3.883 0 7.767-.49 11.422-1.227l4.797 17.173c.457 2.208 2.513 3.68 4.34 3.68.457 0 .914 0 1.143-.246 2.513-.736 3.883-3.434 3.198-6.133l-4.797-17.172c7.767-2.944 14.848-7.114 20.788-11.53l12.336 13.738c.913.981 2.056 1.472 3.198 1.472s2.284-.49 3.198-1.472c1.828-1.963 1.828-4.906.228-6.87l-11.65-13.001c9.366-7.36 14.849-14.474 14.849-14.474z"/></svg>
4、全域性引入svg:
main.ts:
import SvgIcon from '@/components/SvgIcon' // 引入自定義元件 const req = require.context('./icons/svg', false, /\.svg$/); const requireAll = (requireContext: any) => requireContext.keys().map(requireContext); requireAll(req) createApp(App).component("svg-icon", SvgIcon).mount('#app');
頁面上使用:
<template> <div> 交易資訊<br/> <svg-icon icon-class="eye" class-name="card-panel-icon"/><br/> <svg-icon icon-class="eye-open" class-name="card-panel-icon"/> </div> </template>