渲染一个复选框并根据从一个数据集到另一个数据集的值的存在来检查它

Render a checkbox and check it based on the existence of a value from a dataset to another dataset

我的想法是检查一个值是否存在从一个数据集到另一个数据集。在这种情况下,我想使用 id 属性.

我正在尝试handlebars.js,但是下面是无效的。

spot_categories数组

{spot_categories:[{category:1},{category:2},{category:3},{category:4},{category:5},{category:6}]}

数据数组

{data:[{spot_category_id:1},{spot_category_id:3}]}

vue.js代码

<!-- if have var -->
{{# var ok = false}}
<!-- one for -->
<li v-for="(category,j) in spot_categories">
  <label>
        <!-- two for -->
        <template v-for="(val, l) in data">
           <!-- if -->
           <template v-if="val.spot_category_id == category.id">
              {{ ok = true }}
           </template>
        </template>
        <!-- if ok = true , show value -->
        <input :value="category.id" :checked="ok">
  </label>
</li>

我该怎么办?请帮我。谢谢!

您正在考虑使用 spot_categories 数据集在模板中仅循环一次,然后调用一个方法来评估其 ID 是否存在于另一个数据集上。我使用 v-ifv-else 来决定要呈现哪个复选框元素。然后我在我的评估方法上实现了array.some(),这是最适合这种情况的方法(你可以使用手册 for 循环,但它太长了,如果你想要一个看起来很干净的代码,通常不推荐)。

new Vue({
    el: categoryContainers,
    data: {
      spot_categories: [
        {id: 1},
        {id: 2}
      ],
      data: [
        {spot_category_id: 1},
        {spot_category_id: 3}
      ]
    },
    methods: {
      checkIfExists: function(item1){
         return this.data.some(function(val){ return val.spot_category_id == item1.id });
      }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="categoryContainers">
   <ul>
      <li v-for="(category,j) in spot_categories">
         <label>
            <input type="checkbox" v-if="checkIfExists(category)" :value="category.id" checked>
            <input type="checkbox" v-else :value="category.id">
            {{ 'Category ID ' + category.id }}
       </label>
      </li>
    </ul>
</div>