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

如何为v-for循环数组中的首个<p>标签设置加粗样式

解决方法

你的问题核心是原来的CSS选择器逻辑错误,且无法精准定位到第一个内容为“Hello”的元素,要实现需求需要结合Vue的逻辑给目标元素标记特殊类,再通过CSS针对性设置样式。

步骤1:定位目标元素

通过计算属性找到数组中第一个name为“Hello”的元素(或它的索引):

<script>
export default {
  data() {
    return {
      first: [/* 你的数组数据 */]
    }
  },
  computed: {
    // 找到第一个内容为Hello的元素
    targetHelloItem() {
      return this.first.find(item => item.name === 'Hello')
    }
  }
}
</script>

如果用Vue3的<script setup>:

<script setup>
import { computed } from 'vue'
const first = [/* 你的数组数据 */]
const targetHelloItem = computed(() => first.find(item => item.name === 'Hello'))
</script>

步骤2:给目标元素加特殊类

在v-for渲染时,判断当前元素是否是目标元素,给对应的<p>标签额外添加一个类:

<div v-for="item in first" :key="item.id">
  <p class="cat_name" :class="{ 'bold-first-line': item.id === targetHelloItem?.id }">
    {{ item.name }}
  </p>
</div>

如果数组元素没有id,也可以用索引判断:

<!-- 先修改计算属性为获取索引 -->
<script setup>
import { computed } from 'vue'
const first = [/* 你的数组数据 */]
const firstHelloIndex = computed(() => first.findIndex(item => item.name === 'Hello'))
</script>

<!-- 模板中用索引判断 -->
<div v-for="(item, index) in first" :key="index">
  <p class="cat_name" :class="{ 'bold-first-line': index === firstHelloIndex }">
    {{ item.name }}
  </p>
</div>

步骤3:编写精准的CSS样式

针对特殊类设置首行加粗:

<style scoped>
.cat_name.bold-first-line::first-line {
  font-weight: bold;
}
</style>

这样就能确保只有第一个内容为“Hello”的<p>标签会被加粗首行,其他元素不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:31:35