0
点赞
收藏
分享

微信扫一扫

NodeJS的安装 npm 配置和使用 Vue-cli安装 Vue项目介绍

扬帆远航_df7c 2024-11-09 阅读 7

1. 安装SVG依赖插件

pnpm install vite-plugin-svg-icons -D

2. 在vite.config.ts中配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}

3. 入口文件导入

//main.ts
import 'virtual:svg-icons-register'

4. 创建一个SvgIcon组件

src/components/目录下创建

在该组件内部通过props定制图标样式,颜色,样式

<template>
  <div>
    <!-- svg图标外层容器节点,内部需要与use标签结合使用 -->
    <svg :style="{ width: width, height: height }">
      <!-- xlink:href执行用哪一个图标 -->
      <!-- use标签fill属性可以设置图标的颜色 -->
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup lang="ts">
  defineProps({
    //xlink:href属性值的前缀
    prefix: {
      type: String,
      default: '#icon-'
    },
    //svg矢量图的名字
    name: String,
    //svg图标的颜色
    color: {
      type: String,
      default: ""
    },
    //svg宽度
    width: {
      type: String,
      default: '16px'
    },
    //svg高度
    height: {
      type: String,
      default: '16px'
    }

  })
</script>
<style scoped></style>

使用者只需:

<svg-icon
      prefix="#icon-"
      name="home"
      color="red"
      width="500px"
      height="500px"
></svg-icon>

5. 将svg组件封装为全局组

因为项目很多模块需要使用图标,因此把它封装为全局组件!!!

components文件夹下创建index.ts文件,在该文件内部通过

自定义插件components所有组件注册为全局组件

// 在components文件夹目录下创建一个index.ts文件:
// 用于注册components文件夹内部全部全局组件!!!
// 引入项目中全部的全局组件

import SvgIcon from '@/components/SvgIcon/index.vue'
import Pagination from '@/components/Pagination/index.vue'

//创建一个临时全局对象
const allGloablComponent = { SvgIcon, Pagination }

//对外暴露插件对象
export default {
  //务必叫做install方法
  install(app) {
    Object.keys(allGloablComponent).forEach((key) => {
      //将组件注册为全局组件
      app.component(key, allGloablComponent[key])
    })
  },
}

通过Object.keys()配合for of或forEach 可以遍历对象

6. 在入口文件引入src/index.ts文件,通过app.use方法安装自定义插件

//引用自定义插件所在的文件
import gloablComponent from './components/index';
//注册该插件
app.use(gloablComponent);
举报

相关推荐

0 条评论