Vue动态加载CSS方法汇总

之前总结过菜鸟 🐦 常见问题汇总,现在单独总结下CSS

这里初学者容易出现个问题就是三目运算符怎么用,要熟悉:class:style怎么使用。

直接在:class 里面使用变量

假设我用如下CSS,我想先加载基础样式text,然后根据条件动态的加样式black或者grey

.index {
flex-direction: column;
display: flex;
.item {
width: 48rpx;
height: 32rpx;
justify-content: center;
align-items: center;
display: flex;
padding: 5rpx 0;
.text {
font-size: 22rpx;
}
.back {
font-weight: 500;
color: #333;
}
.grey {
color: #666;
}
}
}
<view class="indexes">
<view class="index">
<view v-for="(item, i) in indexes" class="item" @click="onIndexPress(i)">
<view class="text" :class="activeIndex == i ? 'black' : 'grey'"
>{{ item }}</view
>
</view>
</view>
</view>

:class 里面肯可能有字符串

假设我有如下需求,在一个循环里面有三行,每一行绝对定位,top: 行高*当前的行数,这个时候就要在:class里面写字符串了。不过这里面有个更简单的写法,不用定义 3 个样式了

.view {
width: 692rpx;
.swiper {
.item {
position: relative;
.image {
width: 692rpx;
height: 168rpx;
}
.row {
position: absolute;
flex-direction: row;
display: flex;
left: 0;
width: 100%;
height: 54rpx;
padding-top: 2rpx;
.price {
flex: 1;
align-items: center;
justify-content: center;
display: flex;
.text {
font-size: 24rpx;
}
.black {
font-size: 20rpx;
color: #333;
}
.white {
color: white;
}
}
}
}
}
}
<swiper class="swiper" :autoplay="true" :interval="3000">
<swiper-item v-for="(item, i) in datas" :key="i" class="item">
<image src="https://cloud.cctv3.net/Bwoil/share-table.png" class="image" />
<view
v-for="(ite, j) in item"
class="row"
:style="{ top: j * 54 + 'rpx' }"
:key="j"
>
<view v-for="(it, k) in ite" class="price" :key="k">
<view class="text" :class="k == 4 ? 'black' : 'white'" :key="k"
>{{ it }}</view
>
</view>
</view>
</swiper-item>
</swiper>
作者

江北饮马、江南折花

发布于

2024-03-06

更新于

2024-09-03

许可协议

评论