关于css工具及其使用

184 阅读1分钟

1、UnoCss

超级便利写样式工具,不再为取名字而烦恼~~~官网传递门

  • 安装 yarn add -D unocss
  • vite.config.ts文件引入
import UnoCSS from 'unocss/vite'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    UnoCSS(),
  ],
})
  • 创建自定义uno.config.ts设置
import { defineConfig } from 'unocss'

export default defineConfig({
  // ...UnoCSS options
})
  • 添加在入口文件main.ts
import 'virtual:uno.css'
  • 使用: flex布局 高150px 上下居中 间隔20px
<div class="flex items-center h-150px gap-20px">
    <div>unocss</div>
    <div>flex</div>
</div>

一般在小鲸鱼上查询api,只需告诉他要实现的css他会告诉你对应的uno-css怎么写,多问多写就记得差不多了。

2、使用本地svg图标

背景:vue3+antdesignvue

  • 安装 yarn add -D vite-plugin-svg-icons
  • 创建svg组件
<script setup lang="ts">
import { computed, toRefs } from "vue"

const props = defineProps({
    name: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: '#333'
    },
    className: {
        type: String,
        default: ''
    }
})
const {className,color,name} = toRefs(props)
const symbolId = computed(() => `#icon-${name.value}`)
const svgClass = computed(() => {
    return [
        'svg-icon',
        className.value
    ]
})
</script>

<template>
    <svg aria-hidden="true" :class="svgClass">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>

<style scoped lang="less">
/*
 * currentColor: 表示当前元素的color值,如未设置,则取父元素的color值
 * vertical-align: -0.1em:因icon大小跟字体大小一致,而span等标签的小边缘会和字体的基线对齐,所以需要调整下位置
*/
.svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.1em;
    fill: currentColor;
    overflow: hidden;
}
</style>
  • main.ts中注册
import 'virtual:svg-icons-register';
import JSvg from "@/components/global/JIcon/Svg.vue";
...
app.component("JSvg", JSvg);
  • vite.config.ts中配置
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
  plugins: [
    vue(),
    ...
    UnoCSS(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), "src/assets/svgs")],
      symbolId: "icon-[dir]-[name]"
    })
  ],
....
  • 在组件中使用
<JSvg name="home_icon" />

home_iconassets/svgs/home_icon.svg文件