如何通过 vue.js 自动插入 SVG 图标?

如何在 vue.js 中按类型attr显示图标?


HTML


<icon type="heart"></icon>

<icon type="heartFull"></icon>

视图


Vue.component('icon', {

data: {

    type: {

        heart: '<g stroke-linecap="round" stroke-linejoin="round" stroke-width="2" fill="#c3cad5" stroke="#c3cad5"><path fill="none" stroke="#c3cad5" stroke-miterlimit="10" d="M21.243,3.757 c-2.343-2.343-6.142-2.343-8.485,0c-0.289,0.289-0.54,0.6-0.757,0.927c-0.217-0.327-0.469-0.639-0.757-0.927 c-2.343-2.343-6.142-2.343-8.485,0c-2.343,2.343-2.343,6.142,0,8.485L12,21.485l9.243-9.243C23.586,9.899,23.586,6.1,21.243,3.757z"></path></g>',

        heartFull: '<g fill="#c3cad5"><path fill="#c3cad5" d="M21.95,3.051C20.627,1.729,18.87,1,17,1s-3.627,0.729-4.949,2.05C12.034,3.067,12.017,3.084,12,3.102 c-0.017-0.018-0.033-0.034-0.05-0.051C10.627,1.729,8.87,1,7,1S3.373,1.729,2.05,3.051S0,6.13,0,8s0.728,3.627,2.05,4.949l9.95,9.95 l9.95-9.95C23.272,11.627,24,9.87,24,8C24,6.131,23.272,4.373,21.95,3.051z"></path></g>'

    }

},

props: {

    width: {

        type: Number,

        default: 24

    },

    height: {

        type: Number,

        default: 24

    },

},

computed: {

        viewBox() {

            return '0 0 ' + this.width + ' ' + this.height

        }

    },

template: '<svg xmlns="http://www.w3.org/2000/svg" :viewBox="viewBox" :width="width" :height="height">{{ type }}</svg>',

})

预期结果


<icon type="heart"></icon>


<icon type="heartFull"></icon>

它变成


<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24" width="24" height="24"><g fill="#c3cad5"><path fill="#c3cad5" d="M21.95,3.051C20.627,1.729,18.87,1,17,1s-3.627,0.729-4.949,2.05C12.034,3.067,12.017,3.084,12,3.102 c-0.017-0.018-0.033-0.034-0.05-0.051C10.627,1.729,8.87,1,7,1S3.373,1.729,2.05,3.051S0,6.13,0,8s0.728,3.627,2.05,4.949l9.95,9.95 l9.95-9.95C23.272,11.627,24,9.87,24,8C24,6.131,23.272,4.373,21.95,3.051z"></path></g></svg>

通过这种方式,我会随着时间的推移创建更多图标并轻松使用它们。谢谢!


哔哔one
浏览 186回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript