在 Vue 專案中使用 Tailwindcss

Stephen Lai
3 min readMar 2, 2021

感覺不出有甚麼不同呢 😜

我喜歡 Vue 單一組件檔案的開發方式, html, css, javascript 都寫在一個檔案內, 方便開發管理, 不需要像 react 要另外引入 css 檔案 (現在 styled component 讓 react 可以做到單一檔案組件; Next 有 jsx 的 style 可以在 component 內寫 css), angular 更扯把 html, css, js 全部拆開. 單一組件檔案的好處是當我們在寫 css 不需要在 vscode 開兩個視窗. 組件的 html 標籤通常都不會很多, 所以把 html, css, js 寫在一起並不會造成開發上的困擾, 只會讓開發更便利.

最近用 tailwindcss 用上癮了, 因為 utility class 真的很方便, 功能強大且齊全. 最強大的地方是不需要寫 css, 全部在 html 標籤內作業即可. 不過我不喜歡寫落落長的 class, 所以我用到 `@apply` decorator 很多, 我通常都會把所有的 class 寫在 '@apply`, 在 html 標籤只用到一個 class, 舉例來說:

// HTML
<template>
<div class="card">
<img src=path>
<div class="content">
<h3>card title</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing</p>
</div>
</div>
</template>
// Tailwindcss
<style scoped>
.card {
@apply max-w-screen-lg mx-auto border border-green-500;
}
.content {
@apply py-4 px-8 border shadow-lg;
}</style>

可是我發覺這樣的 tailwindcss 寫法和用純 css 寫差異並不大呀

// CSS
<style scoped>
.card {
max-width: 1024px;
margin: auto;
border: 1px solid green;
}
.content {
padding: 1rem 2rem;
border: 1px solid;
box-shadow: 5px 10px;
}

Tailwindcss 的推薦用法是把所有 class 寫在 html 標籤內, 像以下這樣, 才是 tailwind 的作者 Adam Watham 強調的 ~ Youn never leave your html

<template>
<div class="max-w-screen-lg mx-auto border border-green-500">
<img src=path>
<div class="py-4 px-8 border shadow-lg">
<h3>card title</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing</p>
</div>
</div>
</template>

所以對於喜歡乾淨程式碼的人來說, tailwindcss 和 pure css 其實沒有差異, 所以對於喜歡在標籤內寫落落長 class 的朋友來說, tailwindcss 就是最好的朋友 😄😄😄

--

--