vuejs if / else:检查元素是否存在,否则添加元素

时间:2020-01-01 14:35:51

标签: javascript vue.js vuejs2

我有一个v-for,就像这样:

            <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>

效果很好。但是,我想做的是No user responses失败时说some_condition_is_true,但是如果我添加v-else,则消息(无用户响应)将在每个循环中打印,这是当然不想要。如何解决这个问题?

为此,我想知道是否可以测试元素item.id + '__UR'" is present and if not add an element with text saying没有用户响应`

但是我不确定这是否是正确的方法。

编辑

仅需重申:在v-if之前不使用v-for,因为要迭代的对象是嵌套的JSON,然后通过一些vuejs过滤器进行过滤,所以是的,这不是一个选择

2 个答案:

答案 0 :(得分:2)

请注意,boolVar对应于包含bool的实际对象键


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>

答案 1 :(得分:1)

您可能可以使用CSS来实现:

ol + .no-responses {
  display: none;
}

下面有一个完整的示例,但其想法只是将消息隐藏在<ol>之后。调整选择器以反映您的实际用例。

我试图使示例中的模板与原始代码完全相同,并增加了相关消息和几个用于演示目的的按钮。

new Vue({
  el: '#app',
  delimiters: ['[[', ']]'],
  
  data () {
    return {
      UserResponses: []
    }
  },
  
  methods: {
    add () {
      this.UserResponses.push(
        { some_condition: 3, _is_true: 3, id: 3, some_variable_to_render: 'A' },
        { some_condition: 3, _is_true: 4, id: 4, some_variable_to_render: 'B' },
        { some_condition: 4, _is_true: 4, id: 5, some_variable_to_render: 'C' },
        { some_condition: 5, _is_true: 5, id: 6, some_variable_to_render: 'D' }
      )
    },
    
    clear () {
      this.UserResponses.splice(0)
    }
  }
})
ol + .no-responses {
  display: none;
}
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>

<div id="app">
  <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>
  <p class="no-responses">No user responses</p>
  <button @click="add">Add values</button>
  <button @click="clear">Clear values</button>
</div>

相关问题