Search code examples
javascriptvue.jsvuejs2

vuejs if/else: check if element exsists else add a element


I have a v-for like so:

            <p> User Responses(s):</p>
        <template v-for="item in UserResponses">
          <ol v-if="item.some_condition==item._is_true">
            <li :name="item.id + '__UR'"> [[ item.some_variable_to_render ] ]] </li>
          </ol>
      </template>

Works great. However, what I would like to do is say No user responses when the some_condition_is_true fails, but if I add an v-else the message (No user responses) will be printed in every loop, which is not desired ofcourse. How does one solve this problem?

To this end, I wondered if I could test if the element item.id + '__UR'" is present and if not add an element with text sayingNo user responses`

I am not sure however that this is the correct way to go about this.

EDIT

Just to reiterate: using v-if before v-for is not an option since the object being iterated on is a nesed JSON which then is filtered through some vuejs filters, so yea, this is not an option.


Solution

  • note that boolVar corresponds to your actual object key that contains the bools

    
    let model.flag = true
    
    function foo(val) => {
      model.flag = val
      return val
    }
    
    <p> User Responses(s):</p>
    <template>
      <div v-if="model.flag">
        <div v-for="item in UserResponses"   >
          <ol v-if="foo(item.Boolvar)" >
            <li :name="item.id + '__UR'"> [[ item.some_variable_to_render ] ]] </li>
          </ol>
        </div>
      </div>
      <h1 v-else>No user responses 😢</h1>
    </template>