解放双手,css/less/scss收割机,tailwindcss使用心得

1,595 阅读1分钟

前言

传统的vue文件,我们会将代码分为三个部分

<template></template><script setup lang="ts"></script><style scoped lang="less"></style>

我们一般会把css样式放在style中,但如果我们的页面样式足够复杂,我们需要不断的为我们的元素起类名,比如这样:

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
​
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
​
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
​
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
​
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
​
  .title-container {
    position: relative;
​
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
​
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
​
  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
​
}

随着需求不断增加,各种wrap、container、inner不断的增加,会使我们陷入无限的起名字烦恼中😣😣😣,当然,有时候团队会有诸如BEM这样的命名规范,这样看似规范,但其实严重增加了我们的工作量。

解放双手

本着解放双(mo)手(yu)的指导思想,多方寻找资料,最后我们选型tailwindcss,以解决目前团队面临的痛点,具体如何安装可以在tailwind官网查看,我们仅需要在postcss中加入插件,做一些相关的初始化即可

最后我们的代码结构可能是这样

<template>
  <div
    class="max-w-sm px-8 py-8 mx-auto space-y-2 bg-white shadow-md rounded-xl sm:py-4 sm:flex sm:items-center sm:space-y-0 sm:space-x-6"
  >
    <img
      class="block h-24 mx-auto rounded-full sm:mx-0 sm:flex-shrink-0"
      src="/img/erin-lindford.jpg"
      alt="Woman's Face"
    />
    <div class="space-y-2 text-center sm:text-left">
      <div class="space-y-0.5">
        <p class="text-lg font-semibold text-black">Erin Lindford</p>
        <p class="font-medium text-gray-500">Product Engineer</p>
      </div>
      <button
        class="px-4 py-1 text-sm font-semibold text-purple-600 border border-purple-200 rounded-full hover:text-white hover:bg-purple-600 hover:border-transparent focus:outline-none focus:ring-2 focus:ring-purple-600 focus:ring-offset-2"
      >
        Message
      </button>
    </div>
  </div>
</template>
​
<script></script>

省去了<style scoped lang="less"></style>这一层结构,当然如果我们想像less或scss一样封装一些公用的样式,tailwind也是支持的,我们可以将一些公用的样式抽离出来,方便其他地方调用

<button class="btn-indigo">按钮</button><style>
.btn-indigo {
    @apply py-2 px-4 bg-indigo-500 text-white font-semibold rounded-lg shadow-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:ring-opacity-75;
 }
</style>

实际应用

在我们实际项目中,其实部分地方我们还需要使用css来写,比如background这个属性,如果引用的是背景图的话,我们仍然需要写css,但其实无论代码规范度还是开发效率,tailwindcss还是值得使用。