首页 > 解决方案 > 如何在带有 v-for 指令的组件内使用三元运算符?

问题描述

工作代码如下所示:

<template lang="pug">
b-carousel.d-none.d-sm-block(
  id='categoryRoulette'
  controls
  no-animation
  :interval='0'
)
  b-carousel-slide(
    v-for="category in chunkedArr"
    :key="category.permalink"
  )
    template(v-slot:img)
      b-card-group(deck)
        b-card(
          v-for="(item, index) in category" :key="index"
          :img-src='item.image'
          img-alt='Image'
          img-top
          tag='article'
          style="min-width: 250px;"
        )
          b-card-text.d-flex.justify-content-center.align-items-center
            h5
              a(href="#") {{ item.title }}
</template>

但是,我需要检查 item.image 是否存在,如果不显示空白图像,如下所示:

<template lang="pug">
b-carousel.d-none.d-sm-block(
  id='categoryRoulette'
  controls
  no-animation
  :interval='0'
)
  b-carousel-slide(
    v-for="category in chunkedArr"
    :key="category.permalink"
  )
    template(v-slot:img)
      b-card-group(deck)
        b-card(
          v-for="(item, index) in category" :key="index"
          :img-src='item.image ? item.image : '../assets/images/blank.png''
          img-alt='Image'
          img-top
          tag='article'
          style="min-width: 250px;"
        )
          b-card-text.d-flex.justify-content-center.align-items-center
            h5
              a(href="#") {{ item.title }}
</template>

但是,这条线不起作用:

:img-src='item.image ? item.image : '../assets/images/blank.png''

如何检查 item.image?也许,还有另一种方式?

标签: javascriptvue.jsconditional-operator

解决方案


您不能'在另一个中使用嵌套',因此将其更改为"

:img-src='item.image ? item.image : "../assets/images/blank.png"'

或者

:img-src="item.image ? item.image : '../assets/images/blank.png'"

推荐阅读