You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js如何为select选择器设置默认值并对选项进行排序

实现方案

核心逻辑

  • 参照sorted数组的优先级对options做排序:出现在sorted中的元素按照sorted的顺序排列,未出现在sorted中的元素排在末尾,保持原有相对顺序
  • 实例挂载完成后,将下拉框绑定的selected变量赋值为排序后数组的第一个元素,即可实现默认选中效果

推荐使用计算属性存储排序后的数组,不修改原始options数据,响应性更好,修改后完整代码如下:

HTML代码

<div id="app">
  <select v-model="selected">
    <option v-for="option in sortedOptions" v-bind:value="option">
      {{ option }}
    </option>
  </select>
  <span>Selected : {{ selected }}</span>
</div>

JS代码

new Vue({
  el: '#app',
  data: {
    selected: '',
    options: [ 'A', 'B', 'C'],
    sorted: [ 'B', 'C']
  },
  computed: {
    sortedOptions() {
      // 拷贝原数组避免修改原始数据
      return [...this.options].sort((a, b) => {
        const indexA = this.sorted.indexOf(a)
        const indexB = this.sorted.indexOf(b)
        // 两个元素都在sorted中,按sorted的顺序排序
        if (indexA !== -1 && indexB !== -1) return indexA - indexB
        // 仅a在sorted中,a排在前面
        if (indexA !== -1) return -1
        // 仅b在sorted中,b排在前面
        if (indexB !== -1) return 1
        // 都不在sorted中,保持原数组的相对顺序
        return this.options.indexOf(a) - this.options.indexOf(b)
      })
    }
  },
  mounted() {
    // 非空判断避免空数组报错
    if (this.sortedOptions.length) {
      this.selected = this.sortedOptions[0]
    }
  }
});

如果需要直接修改原始options数组,可以把排序逻辑迁移到mounted钩子中,无需修改HTML部分的v-for遍历逻辑:

mounted() {
  this.options.sort((a, b) => {
    const indexA = this.sorted.indexOf(a)
    const indexB = this.sorted.indexOf(b)
    if (indexA !== -1 && indexB !== -1) return indexA - indexB
    if (indexA !== -1) return -1
    if (indexB !== -1) return 1
    return 0
  })
  if (this.options.length) {
    this.selected = this.options[0]
  }
}

在示例参数下,排序后选项顺序为B、C、A,默认选中第一个值B,完全符合需求。

内容的提问来源于stack exchange,提问作者Pronicio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:45:04