WindiCss在webpack+vue-cli的实践(四)Shortcuts

211 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

前言

@apply的使用在组件内,而需要在全局中配置,在任一组件都想共享时,应该怎么做呢?答案是Shortcuts, Shortcuts的配置很简单,只需要在windi.config.js中添加一个Shortcuts的对象即可

Shortcuts

举个栗子

windi.config.js

export default {
    shortcuts: {
        'demo-btn-white': 'text-14px text-[#000] bg-[#fff] rounded-2px border-[#d9d9d9] border-1',
        'demo-btn-black': 'text-14px text-[#fff] bg-[#000] rounded-2px border-[#d9d9d9] border-1',
    }

html

<div class="demo-btn-white btn-items">demo-btn-white</div>
<div class="demo-btn-black btn-items">demo-btn-black</div>

css

.btn-items{
   @apply w-150 h-30 m-30 flex justify-center items-center;
}

其中会被渲染为

.demo-btn-white {
    // .btn-items style
    display: flex;
    align-items: center;
    justify-content: center;
    height: 7.5rem;
    margin: 7.5rem;
    width: 37.5rem;
    // config style
    --tw-bg-opacity: 1;
    background-color: rgba(255, 255, 255, var(--tw-bg-opacity));
    --tw-border-opacity: 1;
    border-color: rgba(217, 217, 217, var(--tw-border-opacity));
    border-radius: 2px;
    border-width: 1px;
    font-size: 14px;
    line-height: 1;
    --tw-text-opacity: 1;
    color: rgba(0, 0, 0, var(--tw-text-opacity));
}

.demo-btn-black {
    // .btn-items style
    display: flex;
    align-items: center;
    justify-content: center;
    height: 7.5rem;
    margin: 7.5rem;
    width: 37.5rem;
    // config style
    --tw-bg-opacity: 1;
    background-color: rgba(0, 0, 0, var(--tw-bg-opacity));
    --tw-border-opacity: 1;
    border-color: rgba(217, 217, 217, var(--tw-border-opacity));
    border-radius: 2px;
    border-width: 1px;
    font-size: 14px;
    line-height: 1;
    --tw-text-opacity: 1;
    color: rgba(255, 255, 255, var(--tw-text-opacity));
}

表现如下

image.png

如果想要更复杂的,比如添加hover,则可以使用css in js的用法

具体用法,稍微修改一下,举个栗子

windi.config.js

export default {
    shortcuts: {
        'demo-btn-white': {
           color: 'black',
           '@apply': 'text-14px bg-[#fff] rounded-2px border-[#d9d9d9] border-1',
           '&:hover': {
             color: 'black',
             '@apply': 'bg-[#fdfdfd] border-[#d9d9d9]',
           },
        },
        'demo-btn-orange': {
           color: 'white',
           '@apply': 'text-[#fff] text-14px bg-[#f08300] rounded-2px',
           '&:hover': {
             color: 'white',
             '@apply': 'bg-[#f07800] text-[#fff]',
           },
      },
    }

其余不变,其表现如下

image.png

结尾

这个特性和 @apply 很类似,其区别在于组件和全局的使用,当然Shortcuts的使用不建议使用过多,正常来讲,一个项目的设计图内会涉及到的全局类会有,但不会特别多

就像Vue中组建通信 这么多,就不要把所有的通信都通过Vuex里,这一部分是我跟别人交流的时候,发现有人做了几年前端了,一问通信竟然只会Vuex,这样的做法是不建议的