Update:
Due to my own fault of not mentioning, that tool
is created in a v-for
loop during render, I couldn’t apply the proposed answers although they might have been correct.
In the end I did a workaround by adding following css sudo element
to the parent of the select
element:
&::after { position: absolute; content: 'Paragraph'; margin-right: .83rem; font-size: .83rem; place-self: center; }
and setting it to display: none
, when an item is selected.
Original Question:
I’m creating a select
element in vue 3
with help of v-for
:
<template> <select v-model="tool.action" @change="selectType(tool.action)"> <option v-for="option in options" :key="option" :value="option.value">{{ option.text }}</option> </select> </template> <script setup> const options: [ { text: 'Heading 1', value: 'h1' }, { text: 'Heading 2', value: 'h2' }, { text: 'Heading 3', value: 'h3' }, { text: 'Paragraph', value: 'p' }, ] </script>
Now I want to set a placeholder
text in the select box
to Paragraph
. Usually it would work like this:
<select> <option value="p" selected>Paragraph</option> </select>
but v-for
removes the option of setting selected
manually so how do I do it?
Advertisement
Answer
A <select>
‘s placeholder is usually disabled and not one of the available options. You can do that with an <option>
before your v-for
of selectable <option>
s:
<template> <select v-model="tool.action" @change="selectType(tool.action)"> <option disabled value="">Placeholder Option</option> 👈 <option v-for="option in options" :key="option" :value="option.value">{{ option.text }}</option> </select> </template>
If you actually want to set the <select>
‘s initial value, you could set the <select>
‘s model (i.e., tool.action
) to the desired value:
<script setup> ⋮ tool.action = 'p' // initialize to 'Paragraph' option's value </script>