<template>
  <div>
    <div v-for='option in options' :key='option.id'>
      <input type='checkbox' v-model='selectedOptions' :value='option.id'>
      <label>{{ option.name }}</label>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      options: [], // 后端返回的选项数据
      selectedOptions: [] // 已选中的选项
    };
  },
  mounted() {
    // 模拟后端返回的数据
    this.options = [
      { id: 1, name: '选项1' },
      { id: 2, name: '选项2' },
      { id: 3, name: '选项3' }
    ];
    
    // 假设已有的数据为[1, 3]
    this.selectedOptions = [1, 3];
  }
};
</script>
<p>在上面的示例中,通过 v-model 指令将多选框绑定到 selectedOptions 数组,然后通过循环遍历 options 数组,并判断 option.id 是否在 selectedOptions 数组中,来决定多选框是否应该勾选。在 mounted 钩子中,您可以将后端返回的数据赋值给 options 数组,并将已有的数据赋值给 selectedOptions 数组,这样多选框就会默认勾选已有的数据。</p>

原文地址: https://www.cveoy.top/t/topic/p8RU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录