You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue实现置顶博客文章差异化CSS样式问题求助

问题描述

尝试为置顶(pinned)博客文章设置差异化CSS样式,但现有代码仅部分生效:每篇文章卡片中都会渲染所有文章的标题,且只有置顶文章的标题能应用目标样式。

错误原因

核心问题是嵌套了两个冲突的v-for循环:

  • 外层已经通过v-for="(post, index) in collection"遍历每篇文章生成独立卡片
  • 内层又重复用v-for="(post, index) in posts"遍历所有文章,导致每个卡片里都渲染了全部文章的标题
  • 内层循环的post变量直接覆盖了外层的post变量,还会导致后续的{{ post.fullText }}等内容出现逻辑混乱

修正方案

移除内层的v-for循环,直接基于当前卡片对应的post对象渲染标题并绑定样式:

修正后的HTML代码

<div class="row card-columns">
  <div class="card-columns">
    <div class="col justify-content-center card text-white bg-dark" v-for="(post, index) in collection" :key="index" :post="post" :index="index">
      <div class="row g-0">

        <img :src="post.image" class="h-100 card-img" alt="Card image cap" style="object-fit: cover;">

        <div class="col-sm-20">
          <div class="card-body">
            <!-- 移除内层v-for,直接使用当前卡片的post对象 -->
            <div :class="{ 'pinned': post.pinned }">
              <h3 class="card-title">{{ post.title }}</h3>
            </div>
            
            <p class="truncate" onclick="RevealHiddenOverflow(this)" style="text-align: left">
                {{ post.fullText }}</p>

            <div class="btn-group flex-column flex-md-row" role="group" aria-label="btn">
              <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#readPost" v-on:click="readPost(post, index)">Show</button>
              <button type="button" class="btn btn-success" data-toggle="modal" data-target="#editPost" v-on:click="editPost(post, index)">Edit</button>
              <button type="button" class="btn btn-danger" v-on:click="deletePost(post)">Delete</button>
            </div>        

          </div>
          
          <div class="card-footer">
            <p class="card-text">{{ post.tags }}</p>
          </div>
          
        </div>
      </div>
    </div>
  </div>
</div>

补充说明

  1. 确保外层循环的collection数组和posts数组数据一致,或者直接将外层循环改为v-for="(post, index) in posts"(根据实际业务逻辑选择)
  2. 定义pinned类的CSS样式以实现差异化,示例:
.pinned .card-title {
  color: #ffd700;
  border-left: 4px solid #ffd700;
  padding-left: 8px;
}

内容的提问来源于stack exchange,提问作者TCGPlaza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:45:33