vue3+js+vite学习之使用svg图标,并且支持svg图标渐变色

使用vite-plugin-svg-icons

1、安装vite-plugin-svg-icons

npm install vite-plugin-svg-icons
或者
yarn add vite-plugin-svg-icons

2、在vite.config.js中进行配置

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default ({ mode }) => {
  const base = '/'
  return defineConfig({
    base,
    plugins: [
      vue(),
      createSvgIconsPlugin({
        // 指定要缓存的图标文件夹(将所有svg都放在一个文件夹下)
        iconDirs: [path.resolve(process.cwd(), 'public/icons')],
        // 执行icon name的格式(dir代表文件夹名称,name代表icon名称)
        symbolId: 'icon-[dir]-[name]'
      })
    ]
  })
}
 

3、组件封装(支持渐变色)

在src/components文件夹下新建SvgIcon文件夹,然后在SvgIcon文件夹下新建index.vue文件

<template>
  <svg :class="svgClass" aria-hidden="true">
    <defs>
      <linearGradient :id="`gradient-${randomNum}`" v-bind="direction">
        <stop :stop-color="props.color" />
        <stop offset="1" :stop-color="props.gradientColor" />
      </linearGradient>
    </defs>
    <use :xlink:href="iconName" :fill="svgFill" />
  </svg>
</template>
<script setup>
import { computed } from 'vue'
let randomNum = Math.random();

const props = defineProps({
  // 图标名称
  name: {
    type: String,
    required: true
  },
  // 单一颜色
  color: {
    type: String,
    default: ''
  },
  // 渐变色
  gradientColor: {
    type: String,
    default: ''
  },
  // 渐变色角度
  gradientAngle: {
    type: String,
    default: '1'
  }
})
// svg的外层div的class
const svgClass = computed(() => {
  if (props.name) {
    return `svg-icon icon-${props.name}`
  } else {
    return 'svg-icon'
  }
})
// svg图标的名称
const iconName = computed(() => {
  return `#icon-${props.name}`
})
// svg填充颜色,如果gradientColor值存在,就是渐变色,否则是单一颜色
const svgFill = computed(() => {
  if (props.gradientColor) {
    return `url(#gradient-${randomNum})`
  }
  return props.color
})
// 渐变色方向
const direction = computed(() => {
  switch (props.gradientAngle) {
    case '1':
      return { x1: '0%', x2: '100%', y1: '0%', y2: '0%' }
    case '2':
      return { x1: '0%', x2: '100%', y1: '100%', y2: '0%' }
    case '3':
      return { x1: '0%', x2: '0%', y1: '100%', y2: '0%' }
    case '4':
      return { x1: '100%', x2: '0%', y1: '100%', y2: '0%' }
    case '5':
      return { x1: '100%', x2: '0%', y1: '0%', y2: '0%' }
    case '6':
      return { x1: '0%', x2: '100%', y1: '0%', y2: '100%' }
    case '7':
      return { x1: '0%', x2: '0%', y1: '0%', y2: '100%' }
    case '8':
      return { x1: '100%', x2: '0%', y1: '0%', y2: '100%' }
    default:
      return { x1: '0%', x2: '100%', y1: '0%', y2: '0%' }
  }
})
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

4、在main.js中注册

// 引入注册脚本
import 'virtual:svg-icons-register'
// 引入组件
import SvgIcon from '@/components/SvgIcon/index.vue'
// 全局组件挂载
app.component('SvgIcon', SvgIcon)

5、使用

<template>
  <svg-icon name="icon-home" color="#f00"/>
  <svg-icon name="icon-back" color="#f00" gradientColor="#0f0" gradientAngle="8" />
</template>

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
作为语言模型,我无法实际编写和运行代码,但我可以向您介绍Vue 3和Vite以及如何使用它们编写ToduList应用程序的步骤。 Vue 3是一个流行的JavaScript框架,用于构建交互式应用程序和用户界面。它具有易于学习使用的API和一些新功能,例如Composition API和Teleport。 Vite是一个快速的现代构建工具,专为大型Web项目而设计。它提供了快速的开发服务器和即时热更新功能。 现在,让我们开始使用Vue 3和Vite构建ToduList应用程序的步骤。 第一步:安装Vite 使用npm安装Vite ``` npm install -g vite ``` 第二步:创建Vue 3项目 通过在终端中运行以下命令,在新的Vue 3项目中使用Vite ``` npm init vite@latest my-todo-list ``` 或使用npx安装和创建一个新的Vue 3项目 ``` npx create-vite-app my-todo-list --template vue ``` 这将创建一个名为' my-todo-list '的新目录并初始化一个基本的Vue 3项目结构。 第三步:安装和配置所需的依赖项 使用以下命令安装axios,用于从后端API获取数据 ``` npm install axios ``` 在'todo list/src'文件夹里新建一个'Api.js'文件: ``` import axios from 'axios' const apiClient = axios.create({ baseURL: `http://localhost:8000/`, // change to API URL headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }) export default { getTodos() { return apiClient.get('/todos') }, editTodoStatus(id, data) { return apiClient.put(`/todos/${id}`, data) }, addNewTodo() { return apiClient.post('/todos') }, deleteTodoById(id) { return apiClient.delete(`/todos/${id}`) } } ``` 第四步:定义应用程序 编辑'todo list/src/App.vue'文件 ``` <template> <div class="container"> <h1 class="text-4xl text-center my-8"> TODO LIST </h1> <div class="my-8"> <button @click.prevent="addNewTodo" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> Add New Todo </button> </div> <div class="my-8"> <ul> <li v-for="todo in todos" :key="todo.id" class="mb-4"> <div class="flex justify-between items-center"> <div> <input type="checkbox" :checked="todo.completed" @change="toggleCompletion(todo)" class="mr-2" /> <span class="font-bold">{{todo.title}}</span> </div> <div class="flex"> <button class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg" @click.prevent="deleteTodoById(todo.id)"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="h-5 w-5"> <path fill-rule="evenodd" d="M14.823 1.77a.75.75 0 01-.06 1.06L10.56 6.25l4.204 4.424a.75.75 0 11-1.12 1.012L9.25 7.812l-4.344 4.575a.75.75 0 01-1.12-1.012L7.93 6.25.765 1.832a.75.75 0 111.06-1.06L9.25 5.688l5.573-5.918a.75.75 0 011.001-.106z" clip-rule="evenodd" /> </svg> </button> </div> </div> </li> </ul> </div> </div> </template> <script> import Api from '@/Api' export default { name: 'App', data() { return { todos: [] } }, async created() { await this.fetchData() }, methods: { async fetchData() { const { data: todos } = await Api.getTodos() this.todos = todos }, async toggleCompletion(todo) { await Api.editTodoStatus(todo.id, { completed: !todo.completed }) await this.fetchData() }, async addNewTodo() { await Api.addNewTodo() await this.fetchData() }, async deleteTodoById(id) { await Api.deleteTodoById(id) await this.fetchData() } } } </script> <style> /* ... */ </style> ``` 第五步:运行程序 使用以下命令运行程序 ``` npm run dev ``` 现在在浏览器中访问'http:// localhost:3000'即可看到ToduList应用程序。 可以使用Api.js文件里的接口完成每操作,此处用axios调用后台API进行模拟,并未真正实现后端API。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值