Set default value to option select menu

I want to bind a custom attribute to an option select menu. The <option> tag would simply have an attribute of selected="selected"

<template>
  <div>
    <select>
      <option v-for="" v-bind:selected="[condition ? selected : notSelected]" value="">{{ resource.xprm_name }}</option>
    </select>
  </div>
</template>

data: {
  selected: "selected",
  notSelected: ""
}

This does not work, but if I change v-bind:selected to v-bind:class then it receives the appropriate class, so the logic is working, but not with the selected attribute.

Any way to make it work with such custom attributes?


Solution 1:

You can just use v-model for selecting a default value on a select box:

Markup:

<div id="app">
  <select v-model="selected">
     <option value="foo">foo</option>
     <option value="bar">Bar</option>
     <option value="baz">Baz</option>
  </select>
</div>

View Model:

new Vue({
  el: "#app",
  data: {
    selected: 'bar'
  }
});

Here's the JSFiddle: https://jsfiddle.net/Lxfxyqmf/

Solution 2:

html:

<div id="myComponent">
    <select v-model="selectedValue">
        <option v-for="listValue in valuesList" :value="listValue">
            {{listValue}}
        </option>
    </select>
    <span>Chosen item: {{ selectedValue }}</span>
</div>

js:

var app = new Vue({
    el: '#myComponent',
    data: {
        selectedValue: 'Two',
        valuesList: ['One', 'Two', 'Three']
    },

Solution 3:

I have created a reusable component of select that also emits the modelValue to parent component.

If you look at the first option tag, you can see how I create a default value using props.

BaseSelect.vue (child component)

<template>
  <label v-if="label">{{ label }}</label>
  <select
    class="field"
    :value="modelValue"
    v-bind="{
      ...$attrs,
      onChange: ($event) => {
        $emit('update:modelValue', $event.target.value);
      },
    }"
  >
    <option value="" disabled>{{ defaultValue }}</option>
    <option
      v-for="option in options"
      :key="option"
      :value="option"
      :selected="option === modelValue"
    >
      {{ option }}
    </option>
  </select>
</template>

<script>
export default {
  props: {
    label: {
      type: String,
      default: ""
    },
    defaultValue: {
      type: String,
      default: "Select an item of the list",
      required: false
    },
    modelValue: {
      type: [String, Number],
      default: "Otros"
    },
    options: {
      type: Array,
      required: true
    },
  },
};
</script>

Parent component

<BaseSelect
      label="Asunto"
      defaultValue = "Selecciona un asunto" 
      v-model="contactValues.asunto"
      :options="asuntos"
    />

Notice that you have to receipt correctly this value in your data() (v-model)