首页 文章

如何在vue组件中创建数组?

提问于
浏览
0

我的vue组件是这样的:

<template>
    ...
        <ul class="list-unstyled">
            <li v-for="category in categories">
                ... 
                    <input type="checkbox" :value="category.id" :checked="category.id in_array(categoryCountry)">  
                ...
            </li>
        </ul>
    ...
</template>

<script>
    export default {
        props: ['categoryCountry', 'categories'],
    }
</script>

我想在输入中改变条件

categoryCountry是数组,例如 array(1,2,3)

因此,如果category.id在categoryCountry数组中,那么它将被检查

我该怎么做?

3 回答

  • 0

    The best and simple answer. 使用"includes"它检查数据是否存在于数组中 .

    example:

    [].includes(something);
    

    answer on your codes.

    <input type="checkbox" :value="category.id" :checked="categoryCountry.includes(category.id)">
    
  • 0

    使用v-如果你可以传递一个函数,你可以在vue中创建一个检查你的数组的方法

    checkInArray: (needle, haystack) {
        return haystack.includes(needle)
    }
    

    你的输入

    <input v-if="checkInArray(categoryCountry, categories)"
    

    Array.prototype.includes()返回一个bool true / false,足以满足条件v-if

  • 2

    如果您收到一个数组,并且需要将数组的每个项目显示为输入复选框,则应遍历每个数组项:

    // Template example
    <div id='check_box_sample'>
      <div v-for="category in categoryCountries">
        <input 
          type="checkbox" 
          :id="category"
          :value="category"
          v-model="checkedCategories">
        <label 
          :for="category">
          {{ category }}
        </label>
      </div>
      <br>
      <span>Checked names: {{ checkedCategories }}</span>
    </div>
    

    因此,对于 v-for="category in categoryCountries" 上的每次迭代,您都要创建一个输入类型复选框,您必须定义一个id :id="category" 和一个值 :value="category" ,因为这只是一个简单的例子,我只使用相同的数组项 .

    你可能想看一个working example

    我希望这对你有帮助 .

相关问题