简体   繁体   English

如何禁用选择选项上的值? (vue.js 2)

[英]How to disable value on the select option ? (vue.js 2)

My component is like this :我的组件是这样的:

<div id="demo">
  <div>
    <select class="form-control" v-model="selected" required>
      <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option>
    </select>
    {{selected}}
  </div>
</div>

var demo = new Vue({
  ...
  data() {
    return {
      selected: '',
      options: [{
        id: '',
        name: 'Select Category'
      }]
    };
  },
  ...
})

See full code and demo here : https://fiddle.jshell.net/oscar11/stvct9er/5/在此处查看完整代码和演示: https : //fiddle.jshell.net/oscar11/stvct9er/5/

I want disable "Select Category".我想禁用“选择类别”。 So "Select category" disabled.所以“选择类别”被禁用。 User can not select it.用户无法选择它。 User can only choose a value other than "Select Category".用户只能选择“选择类别”以外的值。

How can I do it?我该怎么做?

You should add option directly in select tag.您应该直接在select标签中添加option

<select class="form-control" v-model="selected" required>
  <option value="" disabled>Select a category</option>
  <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option>
</select>

Also, remove it from data function.此外,将其从data功能中删除。

data() {
  return {
    selected: '',
    options: []
  };
}

I don't recommend you to add this option in the options array, because it is a placeholder attribute for your select .我不建议您在options数组中添加此选项,因为它是您的selectplaceholder属性。

Other option could be to disable that element using a binding其他选项可能是使用绑定禁用该元素

<option v-for="option in options" 
        :disabled="!option.id"
        v-bind:value="option.id">
    {{ option.name }}
</option>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM