unocss使用说明及语法糖学习

准备工作

unocss依赖安装

npm i -d unocss @unocss/preset-uno @unocss/preset-attributify @unocss/preset-icons
  • 后面三个是预设,第一个是常用工具类,第二个是属性化样式支持,第三个是icon支持,一和二基本都要用,三可看情况安装

引入

// vite.config.ts
import type { PluginOption, UserConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Unocss from 'unocss/vite'
import { presetAttributify, presetIcons, presetUno } from 'unocss'
import { rules, shortcuts } from '@/utils/my_uno'

const config: UserConfig = {
  ···
  plugins: [
    Vue(),
    Unocss({
      presets: [
        presetUno(),
        presetAttributify(),
        presetIcons(),
      ],
      rules,
      shortcuts,
    }) as PluginOption[],
  ],
  ···
}

export default config
  • 这里的rule和shortcuts自定义比较多的情况,可以封装起来,方便管理,见下 my_uno.ts
  • 其中rules和shortcuts和unocss中比较重要且灵活好用的自定义规则,rules和shortcuts的区别可以简单地理解为rules是用css对新的原子化规则进行定义,而shortcuts则是用rules对新的原子化规则进行定义,二者的作用其实是一样的。
// my_uno.ts
import type { Rule, UserShortcuts } from 'unocss'

export const rules: Rule[] = [
  ['img-f', { 'width': '100%', 'object-fit': 'contain' }],
  ['w-f', { width: '100%' }],
  [/^fl-(\d+)$/, ([, flex]) => ({ flex: `${flex}` })],
]

export const shortcuts: UserShortcuts = [
  [
    /^f-((c|s|e)(-(c|s|e|b|a))*)$/,
    ([, , align, , justify]) => { // String.prototype.match 的匹配结果会有几种情况
      const matches = [
        { prefix: 'c', value: 'center' },
        { prefix: 's', value: 'start' },
        { prefix: 'e', value: 'end' },
        { prefix: 'b', value: 'between' },
        { prefix: 'a', value: 'around' },
      ]
      let style = ''
      let corr = matches.find(ele => ele.prefix === align)
      style += `flex items-${corr?.value} content-${corr?.value}`
      if (justify) {
        corr = matches.find(ele => ele.prefix === justify)
        style += ` justify-${corr?.value}`
      }
      return style
    },
  ],
]

在main中引入

// main.ts
import { createApp } from 'vue'
import 'uno.css' // unocss should be imported before app, or it makes unocss invalid while you rerun your app
import App from './App.vue'
import 'virtual:unocss-devtools'
import router from '@/router'

const app = createApp(App)
app.use(router)
app.mount('#app')
  • 然后就可以开始使用了
posted @ 2023-06-16 14:24  Mizuki-Vone  阅读(2048)  评论(0编辑  收藏  举报