vue里怎么让el-select多选框里的选中的check选项靠前

295 阅读1分钟

vue里怎么让el-select多选框里的选中的check选项靠前

     <template>
  <el-select v-model="selectedItems" multiple>
    <el-option v-for="option in orderedOptions" :key="option.value" :label="option.label" :value="option.value" :disabled="option.disabled"></el-option>
  </el-select>
</template>

<script>
export default {
  data() {
    return {
      selectedItems: [], // 用于存储选中的选项
      options: [ // 所有的选项
        { value: 1, label: '选项1' },
        { value: 2, label: '选项2' },
        { value: 3, label: '选项3' },
        { value: 4, label: '选项4' },
        { value: 5, label: '选项5' },
      ]
    }
  },
  computed: {
    orderedOptions() {
      const selected = this.selectedItems // 当前选中的选项
      const options = this.options // 所有选项
      const ordered = []
      // 遍历选项,将选中的选项排在前面,未选中的选项排在后面
      options.forEach((option) => {
        const index = selected.indexOf(option.value)
        if (index > -1) {
          ordered[index] = option
        } else {
          ordered.push(option)
        }
      })
      return ordered
    }
  }
}
</script>