简体   繁体   中英

Default Select Option is Multiple Select is not visibly selected. (VueJs3)

I have created a Select Option, in which one option is by default selected. In example one below, the default selected option is visibly selected within the select bar before opening it.

<select v-model="formData.replyMethod">
 <option value="" selected {{ $t(`files.homeName`)}}</option> # This is visibly selected
 <option value="1" selected {{ $t(`files.foo`)}}</option>
 <option value="2" selected {{ $t(`files.bar`)}}</option>
</select>

However when moving to a Computed Property & V-For, the selected option is selected, but not visibly (you have to open the list to see that now), in its place is a blank bar.

What is causing the difference in output between these two ways of creating a list?

Example 2:

<select v-model="formData.replyMethod">
        <option v-bind:value="selectedOption.id" selected>{{ $t(selectedOption.name) }}</option>
        <option v-bind:value="selectOpts.id" v-for="selectOpt in selectOpts">{{ $t(selectOpt.name) }}</option>
        </select>

const selectedOption = computed(() => {
  if(fooBarVariable) {
    let opt =  {id: 1, name: 'Foo'};
    return opt
  }
});

const selectOpts = [{ id: null, name: 'files.placeholder'},{id: 1, name: 'files.reply'},{id: 2, name: 'files.example'}]

When using v-model with select input, don't use selected attribute to set a default value for your select input.

If you're setting the value for each option by selectedOption.id then simply type the id of the option you would like it to be visible in formData.replyMethod .

For example:

 const selectOpts = [{ id: 1, name: 'files.placeholder'}]; const formData = { replyMethod: 1, };
 <select v-model="formData.replyMethod"> <option v-for="option in selectOpts":value="option.id"> {{ option.text }} </option> </select>

This will set an initial value for your input on component mount which will be overridden upon the user action (Same behavior as selected attribute)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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