前端必知必会-Vue Form表单之多选框select多选


<select multiple>

使用 <select> 标签中的 multiple 属性,下拉列表会展开,我们可以选择多个选项。

要选择多个选项,Windows 用户必须按“ctrl”键,而 macOS 用户必须按“command”键。

在 Vue 中使用 <select multiple> 时,我们需要将 <select> 标签与 v-model 连接起来,并为 <option> 标签赋值:

示例
App.vue:

<template>
<h1>在 Vue 中选择多个</h1>
<p>根据您的操作系统,使用“ctrl”或“c​​ommand”键选择多个选项。</p>
<form @submit.prevent="registerAnswer">
<label for="cars">选择一辆或多辆汽车:</label><br>
<select v-model="carsSelected" id="cars" multiple>
<option>Volvo</option>
<option>Saab</option>
<option>Opel</option>
<option>Audi</option>
<option>Kia</option>
</select>
<button type="submit">提交</button>
</form>
<div>
<h3>已提交答案:</h3>
<p id="pAnswer">{
   
   { inpValSubmitted }></p>
</div>
</template>

<script>
export default {
      
      
data() {
      
      
return {
      
      
carsSelected: [],
inpValSubmitted: '尚未提交'
}
},
methods: {
      
      
registerAnswer() {
      
      
if(this.carsSelected) {
      
      
this.inpValSubmitted = this.carsSelected;
}
}
}
}
</script>

<style scoped>
  div {
      
      
    border: dashed black 1px;
    border-radius: 10px;
    padding: 0 20px 20px 20px;
    margin-top: 20px;
    display: inline-block;
  }
  button, select {
      
      
    margin: 10px;
    display: block;
  }
  label {
      
      
    width: 80px;
    padding: 5px;
  }
  label:hover {
      
      
    cursor: pointer;
    background-color: rgb(211, 244, 211);
    border-radius: 5px;
  }
  #pAnswer {
      
      
    background-color: lightgreen;
    padding: 5px;
  }
</style>

总结

本文介绍了Vue Form表单之多选框select多选的使用,如有问题欢迎私信和评论