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

vue-select使用value和input替代v-model时下拉框不关闭,如何编程关闭?

要实现编程式关闭vue-select下拉框,按以下步骤修改代码即可:

步骤1:修正循环内的ref绑定

你使用v-for渲染了多个v-select组件,固定ref值会导致实例引用冲突,需要改为动态绑定和用户id关联的唯一ref:

<div v-for="user in users" key="user.id">
    <v-select
                  :ref="`vSelect_${user.id}`"
                  :value="user.roleName"
                  label="title"
                  :clearable="false"
                  :options="roleCategory"
                  @input="item => ChangeRole(item,user)"
                />
</div>

步骤2:在ChangeRole方法中调用关闭方法

vue-select内置了close()实例方法,可以直接控制下拉框收起,在事件触发后先执行关闭逻辑即可:

methods: {
  ChangeRole(item,user) {
    // 获取当前对应的v-select实例,调用close方法关闭下拉
    // Vue2中v-for绑定的ref会返回数组,需要取下标0的元素获取实例
    const selectInstance = this.$refs[`vSelect_${user.id}`][0]
    selectInstance.close()

    this.$swal({
      title: '你确定吗?',
      text: '你将要修改用户权限!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: '是的,修改!',
      customClass: {
        confirmButton: 'btn btn-primary',
        cancelButton: 'btn btn-outline-danger',
      },
      buttonsStyling: false,
    }).then(result => {
      if (result.isConfirmed) {
        // 注意原代码此处字段匹配错误,选中的item字段为title,没有roleName属性
        user.roleName = item.title 
      }
    })
  } 
}

补充说明

原代码中存在两处可修正的语法/逻辑问题:

  • data配置内的users数组中,对象属性赋值错误使用了等号,需改为冒号:roleName: 'user'
  • roleCategory数组中两个选项的value值重复,可能会导致选中匹配异常,建议修改为唯一值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:24:04