Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the value for <select> without using 'v-model'

Tags:

vue.js

vuejs2

I would like to have something like the following Vue template, but it does not work with the property selectedVal. What is the correct property name?

<select :selectedVal="myList" multiple>
  <option value="abc">ABC</option>
</select>

For <input> the prop to bind is value, but for <select> it does not seem to be documented anywhere. I am looking for the name of the correct prop to bind.

like image 475
Vincent Cantin Avatar asked Mar 27 '26 07:03

Vincent Cantin


1 Answers

I answered because it's difficult to quote code snippet in a comment.

I think you asked this question after looking into the document here, which showed an elegant way to define selected items.

<select v-model="selected">
  <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
  </option>
</select>

Actually, I doubt if there's a v-bind prop performs like this because value is an attribute of input and option, but selected is not an attribute of select but an attribute of option and I can't find any alternatives in select.

Also, after browsing the source code of Vue.js, I didn't see vue did much for binding an attribute (code here and here) rather than pushing values of v-bind into the element's attrs list.

export function addAttr (el: ASTElement, name: string, value: string) {
  (el.attrs || (el.attrs = [])).push({ name, value })
}

On the other hand, select seems to be an special case in v-model (see code here).
So, I provided the solution in the comment by binding selected to option instead of select.

like image 91
choasia Avatar answered Mar 28 '26 21:03

choasia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!