Vue select选中选项后如何自动复位选中第一个默认选项
方案1:直接操作DOM复位(改动最小)
你只需要在selectUser方法的数组操作逻辑结束后,手动把select元素的选中索引设置为0即可,同时注意原代码的option标签存在语法错误,插值表达式要放在标签内容区域,修改后的完整代码如下:
<template> <select class="form-control mt-1" @change="selectUser"> <option>select user</option> <option v-for="(user, index) in users" :key="index">{{user.first_name}}</option> </select> </template> <script> export default { data() { return { users: [], // 你的原用户数组 selectedUsers: [], index: 0 } }, methods: { selectUser(event){ if(event.target.selectedIndex != 0){ this.index = event.target.selectedIndex-1 this.selectedUsers.push(this.users[this.index]) this.users.splice(this.index, 1) // 新增下面这行即可完成复位 event.target.selectedIndex = 0 } } } } </script>
方案2:使用v-model绑定(更符合Vue最佳实践)
如果想要避免直接操作DOM,遵循Vue声明式开发规范,可以给select绑定v-model实现状态控制:
<template> <select class="form-control mt-1" v-model="selectedOptionIndex" @change="selectUser"> <option :value="0">select user</option> <option v-for="(user, index) in users" :key="index" :value="index+1">{{user.first_name}}</option> </select> </template> <script> export default { data() { return { users: [], selectedUsers: [], selectedOptionIndex: 0 // 初始值为0,默认选中第一个选项 } }, methods: { selectUser(){ if(this.selectedOptionIndex != 0){ const targetIndex = this.selectedOptionIndex - 1 this.selectedUsers.push(this.users[targetIndex]) this.users.splice(targetIndex, 1) // 复位绑定值即可自动更新选中状态 this.selectedOptionIndex = 0 } } } } </script>
内容的提问来源于stack exchange,提问作者Penny
相关产品推荐
相关产品推荐

