如何在 v-for 循环中定位 nuxt 组件的第二个实例?

How do I target the second instance of a nuxt component within a v-for loop?

我正在尝试这样做,以便能够将 class 动态绑定到同一 Nuxt 组件的第二个实例中的 DOM 元素。


index.vue

<template>
  <div>
    <div v-for="block in page.fields.blocks">
      <Block v-if="block.fields.style === 'Block'"/>
    </div>
  </div>
</template>

Block.vue

<template>
  <div class="block" v-bind:class="ifThisIsASecondInstance ? 'left' : 'right'">
  </div>
</template>

我认为这可以通过使用 css 来解决。

div > .Block:nth-child(2) {
    // style definition
}

另一种方法是在外循环中绑定 class。

filteredPageFieldsBlocks = page.fields.blocks.filter(b => block.fields.style === 'Block')

<template>
  <div>
    <div v-for="(block, index) in filteredPageFieldsBlocks">
      <Block :class="index === 1 ? 'left' : 'right'"/>
    </div>
  </div>
</template>

How do I target the second instance of a nuxt component within a v-for loop?

我会告诉你具体怎么做

index.vue

<div 
    v-for="(block,index) in page.fields.blocks" 
    :key="block.id">

    <Block 
        v-if="block.fields.style === 'Block'" 
        :index="index"/>
</div>

我假设这是 page.field.blocks

中的信息
page :  {
    fields : {
        blocks : [
            {id:"a1", name:"mars",    fields : {style : "Block"}}, //index 0
            {id:"a2", name:"jupiter", fields : {style : "Block"}}, //index 1
            {id:"a3", name:"saturn",  fields : {style : "Block"}}, //index 2
            {id:"a4", name:"uranus",  fields : {style : "Block"}}, //index 3
            {id:"a5", name:"neptune", fields : {style : "Block"}}  //index 4
        ]
   }
}

v-for="(block,index) 中的 index 对象将包含数组中元素的顺序 page.field.blocks

  • 对于您的用例,我们需要使用这个 index 对象
  • index 对象需要传递给子组件即 Block.vue :index="index"
  • index 对象在 Block.vue 中使用 props
  • 接收

Block.vue

<template>
  <div>
      <div>block.vue</div> 
      <div :class="index == 1 ? 'left' : 'right'">{{index}}</div>
  </div>
</template>

<script>
export default {
  props:["index"]
}
</script>

您的目标是专门检查第二个元素。检查 index == 1 并分配适当的 class :class="index == 1 ? 'left' : 'right'"

更新:

我似乎错过了 @Morty Choi 强调的 simple logic。 以下所有代码更改都应在 index.vue

中完成

创建一个计算 属性 来过滤 style === 'Block' 之前的对象

computed:{
      filterBlocks(){
        return this.page.fields.blocks.filter((data) => data.fields.style === 'Block');
      }
}

然后在index.vue

中使用计算出的属性v-for
<div 
    v-for="(block,index) in filterBlocks" 
    :key="block.id">