My challenge is to bind a <select>
HTML element with the v-model
directive to a ref
value in Vue.js 3's setup()
method. I want the Form.ProductID
ref to be updated when a user selects a different option.
This is the code for the <select>
element:
<select v-model="Form.ProductID" id="ProductID" name="ProductID">
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
</select>
The setup()
method looks like this:
export default {
name: "ComponentProductSelector",
setup() {
const Form = ref({
ProductID: '2',
Price: null,
Currency: null
})
onMounted(() => Form.value.ProductID)
document.querySelector("#ProductID option:first-of-type")
}
}
When inspecting the data in vue devtools on initial load, it displays as follows:
Form (Object Ref)
ProductID: "[object HTMLOptionElement]"
After selecting an option in the <select>
element, Form.ProductID
updates correctly and indicates the selected option, for example:
Form (Object Ref)
ProductID: 3
The issue arises during the component's first render where the <select>
element does not automatically select the option with value="2"
, even though it is hardcoded in the setup()
. It only shows a blank option! However, changing the <select>
element to the following code resolves the issue:
<select ref="Form.ProductID" id="ProductID" name="ProductID">
<option value="1">Option A</option>
<option value="2">Option B</option>
<option value="3">Option C</option>
</select>
Now, the option with value="2"
is selected by default upon rendering the component. However, the actual value of Form.ProductID
does not update, and vue devtools still displays
ProductID: "[object HTMLOptionElement]"
as the data.
Can someone guide me on how to make the <select>
element work using v-model
while also selecting a default option when the component loads?