vue如何动态生成andv图标
作者:木槿-年华
vue动态生成andv图标
在最近使用andv的时候,出现了一个问题,在不使用iconfont图标的前提下使用andv自带的图标库动态生成icon图标。
在百度一下后,发现以下方法
1.新建一个createIcon.js文件
import * as icons from '@ant-design/icons-vue';
import { createVNode } from 'vue'
export const CreateIcon = (props)=>{
const {icon} = props;
return createVNode(icons[icon]);
}2.使用
<a-menu
v-model:selectedKeys="state.selectedKeys"
theme="dark"
mode="inline"
>
<template v-for="item in menus" :key="item.path">
<a-sub-menu
v-if="item.children && item.children.length"
key="item.name"
>
<template #icon>
<CreateIcon :icon="item.icon"></CreateIcon>
</template>
<template #title>{{ item.title }}}</template>
<a-menu-item v-for="itemChild in item.children" :key="itemChild.name">
<span>{{ itemChild.title }}</span>
</a-menu-item>
</a-sub-menu>
<a-menu-item v-else>
<template #icon>
<CreateIcon :icon="item.icon"></CreateIcon>
</template>
<span>{{ item.title }}</span>
</a-menu-item>
</template>
</a-menu>import {CreateIcon} from './CreateIcon.js';
import {Component} from 'vue';
interface routerConfig {
path: string;
name: string;
title: string;
icon?:string|Component,
children?:routerConfig[],
}
const menus:routerConfig[] = [
{
path: "/home",
name: "home",
title: "首页",
icon: 'HomeOutlined',
children: [],
},
];vue动态绑定图标
图标和图片的不同
图标时字符,图片时二进制流。
即图片加载会比图标慢,且加载图标最好不要用img标签,我们可以把图标当成组件用 import 的方法引入进来,然后当成标签引入。
安装 svg
1.使用管理员身份运行cmd窗口,切换到项目目录下执行。
npm add svg
从图标库下载图标
1.阿里图标库
2.下载svg

3.在compone目录下建立一个icons,在icons下建立一个svg目录,专门用来放图标。

查看插件的使用方法
vue所有的插件都在 node_modules
中根据下载时的插件名来找到插件 e-cli-plugin-svg 的 README

展示图标
定义动态组件 MyIcon.vue
1.其中 myicon 是从父组件传过来的属性
2.computed是用来根据 myicon.name (图标的名字)来动态生成图标地址的。原因是在 export default{} 外引入组件时,我们接收到的props属性是传递不到 export default{} 外面的,所以采用computed来协助生成 icon 组件。
3.:style 是动态绑定样式,此处绑定了宽,高。并在props中设置了默认值,如果父组件不传递宽高信息的话,就是使用默认值。
4.:fill 是绑定填充属性样式的,也在 props 中设置了默认值。
<template>
<div>
<component
:is="icon"
:style="{width : myicon.width , hight : myicon.hight}"
:fill="myicon.fill"
></component>
</div>
</template><script>
export default{
props:{
myicon:{
name:{
type:String
},
width:{
type:String,
default:'40px'
},
hight:{
type:String,
default:'40px'
},
fill:{
type:String,
default:'#000000'
}
}
},
computed:{
icon(){
return () => import('@/components/icons/svg/'+ this.myicon.name +'.svg?inline')
}
}
}
</script>
<style>
</style>在main,js中全局引入并定义组件 MyIcon.vue
import mysvg from '@/components/MyIcon.vue'
Vue.component('my-icon',mysvg)调用 my-icon 作为父组件
1.把要传递的属性定义在 myicon:{} 中,其中 name 是必填项,它是图标的名字,不带后缀。
<template> <my-icon :name = "scope.row.icon" :width = "50px" :hight = "50px" :fill = "#ff00ff"> </my-icon> </template>
<script>
export default {
data() {
return {
myicon:{
name: "position",
width: "60px",
hight: "60px",
fill : "#ff00ff"
},
}
},
}
</script>
<style scoped lang="less">
</style>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
