创建项目
pnpm create vite
整合Tailwindcss
安装依赖:
pnpm install -D tailwindcss postcss autoprefixer
生成配置文件:
npx tailwindcss init
postcss.config.js
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}
tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/**/*.{html,js,vue}"],
theme: {
extend: {},
},
plugins: [],
}
src/style.css
@tailwind base;
@tailwind components;
@tailwind utilities;
src/App.vue
<template>
<h1 class="text-3xl font-bold underline">
Hello world!
</h1>
</template>
实现动态渲染样式
<script setup>
const styleStr = "underline"
</script>
<template>
<h1 class="text-3xl font-bold" :class="`${styleStr}`">
Hello world!
</h1>
</template>
可能有问题的代码
<script setup>
import {ref} from "vue";
let prefixes = [
"bg-slate-",
"bg-gray-",
"bg-zinc-",
"bg-neutral-",
"bg-stone-",
"bg-red-",
"bg-orange-",
"bg-amber-",
"bg-yellow-",
"bg-lime-",
"bg-green-",
"bg-emerald-",
"bg-teal-",
"bg-cyan-",
"bg-sky-",
"bg-blue-",
"bg-indigo-",
"bg-violet-",
"bg-purple-",
"bg-fuchsia-",
"bg-pink-",
"bg-rose-"
]
let colorScores = Array.from(Array(10), (v, k) => k * 100)
const colors = ref([])
for (let prefix of prefixes) {
for (let colorScore of colorScores) {
colors.value.push(`${prefix}${colorScore}`)
}
}
</script>
<template>
<div v-for="(color, index) in colors" :key="index" :class="`${color}`">
{{ color }}
</div>
</template>
问题解决
第一步:写死的多个背景
<script setup>
</script>
<template>
<div class="flex gap-3 flex-wrap justify-between p-8 bg-indigo-50">
<div class="w-32 h-12 bg-orange-100"></div>
<div class="w-32 h-12 bg-orange-200"></div>
<div class="w-32 h-12 bg-orange-300"></div>
<div class="w-32 h-12 bg-orange-400"></div>
<div class="w-32 h-12 bg-orange-500"></div>
<div class="w-32 h-12 bg-orange-600"></div>
<div class="w-32 h-12 bg-orange-700"></div>
<div class="w-32 h-12 bg-orange-800"></div>
<div class="w-32 h-12 bg-orange-900"></div>
</div>
</template>
第二步:弄成数组
<script setup>
const colors = [
"bg-orange-100",
"bg-orange-200",
"bg-orange-300",
"bg-orange-400",
"bg-orange-500",
"bg-orange-600",
"bg-orange-700",
"bg-orange-800",
"bg-orange-900",
]
</script>
<template>
<div class="flex gap-3 flex-wrap justify-between p-8 bg-indigo-50">
<div
v-for="(color, index) in colors"
:key="index"
class="w-32 h-12"
:class="color"
></div>
</div>
</template>
第三步:动态拼接更丰富的背景样式类