Vue 3 Dynamically set selected option of select form element - javascript

Using Vue 3, how can I dynamically set the selected option when the data value does not match an available option value?
Condition:
If Florida (FL) is the stored data value for state, and the country is changed from United States (US) to Canada (CA), the State's option value becomes blank. Instead, I would like for the placeholder item to show as the 'selected' option when there is no match.
<template>
<div>
<label v-if="data.country === 'US'">
State
<select v-model="data.state">
<option value="" disabled>state</option>
<option
v-for="(state, i) in states"
:value="state['code']"
:key="i"
>{{ state['name'] }}</option
>
</select>
</label>
<label v-if="data.country === 'CA'">
Province
<select v-model="data.state">
<option value="" disabled>province</option>
<option
v-for="(province, i) in provinces"
:value="province['code']"
:key="i"
>{{ province['name'] }}</option
>
</select>
</label>
</div>
<label>
Country
<select v-model="data.country">
<option value="" disabled>country</option>
<option
v-for="(country, i) in countries"
:value="country['code']"
:key="i"
>{{ country['name'] }}</option
>
</select>
</label>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import data from '...'
import states from '...'
import provinces from '...'
import countries from '...'
export default defineComponent({
setup() {
...
return { data, states, provinces, countries }
},
})
</script>

You could assign a blank value to the placeholder options:
<option value="" disabled>state</option>
<option value="" disabled>province</option>
And use a watcher on data.country to set data.state to the blank value when the country changes:
import { defineComponent, watch } from 'vue'
export default defineComponent({
setup() {
//...
watch(() => data.country, () => data.state = '')
},
})
demo

Related

React JS Routing on 2 Option Values

I am new to React and I'm having a hard time figuring out how to return (or route to) a new page based off of two user selected options? I am trying to load a unique set of buttons for the user to select from depending on the options that they select. When reselecting different options the page would reload with the appropriate buttons.
import React from 'react';
import "./App.css";
import "./styles.css"
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import ObservationText from './components/ObservationText/ObservationText';
import { Dropdown } from 'bootstrap';
/*
let activity = document.getElementById('Activity-Type');
let role = document.getElementById('Role-Type');
activity.addEventListener('change', () => update());
role.addEventListener('change', () => update());
function update(){
const roleValue = document.getElementById('Role-Type').value;
const activityValue = document.getElementById('Activity-Type').value;
//console.log(activityValue + roleValue);
switch (activityValue + roleValue){
case 'ND_A18_FP1VO1-CREW' :
ND_A18_FP1VO1CREW();
break;
default:
//consle.log('this is the default message');
break;
}
}
function ND_A18_FP1VO1CREW(){
alert('ND A18 FP1 + VO1-CREW Selected');
}
*/
function getActivity(el){
const option = el.value;
if(option ==='esc')return
console.log(option)
return option;
}
function getRole(el){
const option = el.value;
if(option ==='esc')return
console.log(option)
return option;
}
function App(){
return (
<div className="App">
<Header/>
<h1>
<label htmlFor ="Activity-Type" className ="sideBySideField">Activity
<select id="Activity-Type" onChange={e => getActivity(e.target)}>
<option value="" disabled="" defaultValue=""> Select... </option>
<option value="ND A18 FP1">ND_A18_FP1</option>
<option value="ND A18 FP2">ND_A18_FP2</option>
<option value="ND BPLANE">ND_BPLANE</option>
<option value="NM A18 FP2">NM_A18_FP2</option>
<option value="AK A18 FP3">AK_A18_FP3</option>
</select>
</label>
<label htmlFor="Role" className ="sideBySideField">Role
<select id="Role-Type" onChange={e => getRole(e.target)}>
<option value="" disabled="" defaultValue=""> Select... </option>
<option value="Other General">Other-General</option>
<option value="VO1 CREW">VO1CREW</option>
<option value="VO2-CREW">VO2CREW</option>
<option value="VO3-CREW">VO3CREW</option>
<option value="VO4-CREW">VO4CREW</option>
<option value="EO2-EO Observer">EO2EO_Observer</option>
<option value="EO1-EO Observer">EO1EO_Observer</option>
<option value="Observer 1-GCS Observer">Observer1GCS_Observer</option>
<option value="FTD-Flight Test Director">FTDFlight_Test_Director</option>
</select>
</label>
</h1>
<div class="center">
<ObservationText/>
</div>
<Footer/>
</div>
);
}
export default App;

Bind Id through another property React [duplicate]

I'm using react and I want to get the value of the selected option of a dropdown in react but I don't know how. Any suggestions? thanks!
My dropdown is just a select like:
<select id = "dropdown">
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
The code in the render method represents the component at any given time.
If you do something like this, the user won't be able to make selections using the form control:
<select value="Radish">
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
So there are two solutions for working with forms controls:
Controlled Components Use component state to reflect the user's selections. This provides the most control, since any changes you make to state will be reflected in the component's rendering:
example:
var FruitSelector = React.createClass({
getInitialState:function(){
return {selectValue:'Radish'};
},
handleChange:function(e){
this.setState({selectValue:e.target.value});
},
render: function() {
var message='You selected '+this.state.selectValue;
return (
<div>
<select
value={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
);
}
});
React.render(<FruitSelector name="World" />, document.body);
JSFiddle: http://jsfiddle.net/xe5ypghv/
Uncontrolled Components The other option is to not control the value and simply respond to onChange events. In this case you can use the defaultValue prop to set an initial value.
<div>
<select defaultValue={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
http://jsfiddle.net/kb3gN/10396/
The docs for this are great: http://facebook.github.io/react/docs/forms.html
and also show how to work with multiple selections.
UPDATE
A variant of Option 1 (using a controlled component) is to use Redux and React-Redux to create a container component. This involves connect and a mapStateToProps function, which is easier than it sounds but probably overkill if you're just starting out.
Implement your Dropdown as
<select id = "dropdown" ref = {(input)=> this.menu = input}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Now, to obtain the selected option value of the dropdown menu just use:
let res = this.menu.value;
It should be like:
import React, { useState } from "react";
export default function App() {
const getInitialState = () => {
const value = "Orange";
return value;
};
const [value, setValue] = useState(getInitialState);
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div>
<select value={value} onChange={handleChange}>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{`You selected ${value}`}</p>
</div>
);
}
you can see it here: https://codesandbox.io/s/quizzical-https-t1ovo?file=/src/App.js:0-572
Just use onChange event of the <select> object.
Selected value is in e.target.value then.
By the way, it's a bad practice to use id="...". It's better to use ref=">.."
http://facebook.github.io/react/docs/more-about-refs.html
As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to
use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple
you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown
whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList
1
remember you will always get the result as option value and not the dropdown text which is displayed on the screen
import React, { Component } from "react";
import { Server } from "net";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {
selectValue: ""
};
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
this.setState({ selectValue: e.target.value });
}
render() {
return (
<div>
<div>
<div>
<select id="dropdown" onChange={this.handleDropdownChange}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>Selected value is : {this.state.selectValue}</div>
</div>
</div>
);
}
}
export default InlineStyle;
Using React Functional Components:
const [option,setOption] = useState()
function handleChange(event){
setOption(event.target.value)
}
<select name='option' onChange={handleChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
class App extends React.Component {
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
And you can check it out on this site.
It is as simple as that. You just need to use "value" attributes instead of "defaultValue" or you can keep both if a pre-selected feature is there.
....
const [currentValue, setCurrentValue] = useState(2);
<select id = "dropdown" value={currentValue} defaultValue={currentValue}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
.....
setTimeut(()=> {
setCurrentValue(4);
}, 4000);
In this case, after 4 secs the dropdown will be auto-selected with option 4.
I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.
In the spirit of the other answers using food examples, I got all sorts of fruit goodness for you.
First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.
Next up, the same example - but juiced up with Typescript.
Then a bonus finale - A language selector dropdown component using Typescript.
Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector
import React, { useState } from 'react'
export const FruitSelectDropdown = () => {
const [currentFruit, setCurrentFruit] = useState('oranges')
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop
import React, { useState } from 'react'
export const FruitSelectDropdown = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
FruitSelectDropdown with Typescript
import React, { FC, useState } from 'react'
type FruitProps = {
fruitDetector: string;
}
export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit: string): void => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App: FC = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
Bonus Round: Translation Dropdown with selected current value:
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
export const LanguageSelectDropdown: FC = () => {
const { i18n } = useTranslation()
const i18nLanguage = i18n.language
const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
const changeLanguage = (language: string): void => {
i18n.changeLanguage(language)
setCurrentI18nLanguage(language)
}
return (
<form>
<select
onChange={(event) => changeLanguage(event.target.value)}
value={currentI18nLanguage}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
)
}
An invaluable resource for React/Typescript
You can handle it all within the same function as following
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>
<option value="5">5 dollars</option>
<option value="10">10 dollars</option>
</select>
as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!
If you want to get value from a mapped select input then you can refer to this example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruit: "banana",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log("Fruit Selected!!");
this.setState({ fruit: e.target.value });
}
render() {
return (
<div id="App">
<div className="select-container">
<select value={this.state.fruit} onChange={this.handleChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
);
}
}
export default App;
import {React, useState }from "react";
function DropDown() {
const [dropValue, setDropValue ]= useState();
return <>
<div>
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
{dropValue==null || dropValue=='' ?'Select Id':dropValue}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" onClick={()=> setDropValue('Action')} href="#">Action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Another action')} href="#">Another action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Something else here')} href="#">Something else here</a></li>
</ul>
</div>
</div>
</>
}
export default DropDown
<select value ={this.state.value} onChange={this.handleDropdownChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
As mentioned by Karen above you can just use the target value from the event triggered. Here is a small snippet of the code
`<select class="form-select py-2"
onChange={(e) => setVotersPerPage(e.target.value)}>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>`

Antd select with multiselection checkboxes

Im using antd's select component and I can render checkboxes inside the select options. But on selecting the checkbox, it changes as tag in the placeholder. How can I just multiselect checkboxes and do not render it as tag in the placeholder
My code is in the link https://codesandbox.io/s/confident-gauss-v7yrv?file=/src/App.js:0-807
import React from "react";
import "./styles.css";
import { Select, Checkbox } from "antd";
import "antd/dist/antd.css";
const { Option, OptGroup } = Select;
export default function App() {
return (
<div className="App">
<Select placeholder="selections" style={{ width: 150 }}>
<OptGroup label="Gender">
<Option value="male">
<Checkbox>Male</Checkbox>
</Option>
<Option value="female">
<Checkbox>Female</Checkbox>
</Option>
</OptGroup>
<OptGroup label="Status">
<Option value="prepaid">
<Checkbox>Single</Checkbox>
</Option>
<Option value="postpaid">
<Checkbox>Married</Checkbox>
</Option>
</OptGroup>
</Select>
</div>
);
}
You can bind a value and never change that for example
<Select placeholder="selections" style={{ width: 150 }} value="">

How can I set selected option selected in vue.js 2?

My component vue is like this :
<template>
<select class="form-control" v-model="selected" :required #change="changeLocation">
<option :selected>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
I use this : <option :selected>Choose Province</option> to selected
But whene executed, on the gulp watch exist error
The error like this :
ERROR in
./~/vue-loader/lib/template-compiler.js?id=data-v-53777228!./~/vue-load
er/lib/selector.js?type=template&index=0!./resources/assets/js/components/bootst
rap/LocationBsSelect.vue Module build failed: SyntaxError: Unexpected
token (28:4)
Seems my step is wrong
How can I solve it?
Handling the errors
You are binding properties to nothing. :required in
<select class="form-control" v-model="selected" :required #change="changeLocation">
and :selected in
<option :selected>Choose Province</option>
If you set the code like so, your errors should be gone:
<template>
<select class="form-control" v-model="selected" :required #change="changeLocation">
<option>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
Getting the select tags to have a default value
you would now need to have a data property called selected so that v-model works. So,
{
data () {
return {
selected: "Choose Province"
}
}
}
If that seems like too much work, you can also do it like:
<template>
<select class="form-control" :required="true" #change="changeLocation">
<option :selected="true">Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
When to use which method?
You can use the v-model approach if your default value depends on some data property.
You can go for the second method if your default selected value happens to be the first option.
You can also handle it programmatically by doing so:
<select class="form-control" :required="true">
<option
v-for="option in options"
v-bind:value="option.id"
:selected="option == '<the default value you want>'"
>{{ option }}</option>
</select>
The simplest answer is to set the selected option to true or false.
<option :selected="selectedDay === 1" value="1">1</option>
Where the data object is:
data() {
return {
selectedDay: '1',
// [1, 2, 3, ..., 31]
days: Array.from({ length: 31 }, (v, i) => i).slice(1)
}
}
This is an example to set the selected month day:
<select v-model="selectedDay" style="width:10%;">
<option v-for="day in days" :selected="selectedDay === day">{{ day }}</option>
</select>
On your data set:
{
data() {
selectedDay: 1,
// [1, 2, 3, ..., 31]
days: Array.from({ length: 31 }, (v, i) => i).slice(1)
},
mounted () {
let selectedDay = new Date();
this.selectedDay = selectedDay.getDate(); // Sets selectedDay to the today's number of the month
}
}
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
You simply need to remove v-bind (:) from selected and required attributes.
Like this :-
<template>
<select class="form-control" v-model="selected" required #change="changeLocation">
<option selected>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
You are not binding anything to the vue instance through these attributes thats why it is giving error.
My code for reactive multiselect
data() {
return {
article: {title: 'aaaaa', 'categoriesIds': [1,3], ...},
selectCategories: {1: 'xxx', 2: 'www', 3: 'yyy', 4: 'zzz'},
}
},
template
<div class="form-group">
<label for="content">Categories</label>
<select name="categories"
v-model="article.categoriesIds"
id="categories"
multiple
class="form-control col-md-5"
size="6">
<option v-for="(category, key) in selectCategories"
:key="key"
v-bind:value="key">{{category}}</option>
</select>
</div>
Selected items are binded to the article.categoriesIds array.
Another way, which I often find more reliable, is you could add a directive to your app.js or wherever you are initiating your VueJS, eg:
Vue.directive('attr', (el, binding) => {
if (binding.value === true) binding.value = ''
if (binding.value === '' || binding.value) {
el.setAttribute(binding.arg, binding.value)
}
})
You can then utilise v-attr to set an attribute, eg:
<option value="Western Australia" v-attr:selected="form.state == 'Western Australia'">Western Australia</option>
So as I understand the main goal is to set "Choose Province" as the default. I tried other options but the simple one worked for me the best:
<template>
<select class="form-control" v-model="selected" :required #change="changeLocation">
<option>Choose Province</option> # just an option with no selected or assigned v-model
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>

Select2 with Vue Js as directive

I have been following the vue js wrapper component example. I am trying to change how this works to allow me to add a v-select2 directive to a regular select box rather than have to create templates and components for each one.
I have a JS Bin here which shows using the component.
The component html is as follows (with the options being set in the JS).
<div id="app"></div>
<script type="text/x-template" id="demo-template">
<div>
<p>Selected: {{ selected }}</p>
<select2 :options="options" v-model="selected">
<option disabled value="0">Select one</option>
</select2>
<p>Selected: {{ selected2 }}</p>
<select2 :options="options" v-model="selected2">
<option disabled value="0">Select one</option>
</select2>
<p>Selected: {{ selected3 }}</p>
<select2 :options="options" v-model="selected3">
<option disabled value="0">Select one</option>
</select2>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
With the JS as follows:
Vue.component('select2', {
props: ['options', 'value'],
template: '#select2-template',
mounted: function () {
var vm = this
$(this.$el)
.val(this.value)
// init select2
.select2({ data: this.options })
// emit event on change.
.on('change', function () {
vm.$emit('input', this.value)
})
},
watch: {
value: function (value) {
// update value
$(this.$el).val(value)
},
options: function (options) {
// update options
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
})
var vm = new Vue({
el: '#app',
template: '#demo-template',
data: {
selected: 0,
selected2: 0,
selected3: 0,
options: [
{ id: 1, text: 'Hello' },
{ id: 2, text: 'World' }
]
}
})
What I want is something like the following
<div id="app">
<p>Selected: {{ selected }}</p>
<select name="selected1" id="selected1" class="select2" v-selectize v-model="selected">
... options here ...
</select>
<p>Selected: {{ selected2 }}</p>
<select name="selected2" id="selected2" class="select2" v-selectize v-model="selected2">
... options here ...
</select>
<p>Selected: {{ selected3 }}</p>
<select name="selected3" id="selected3" class="select2" v-selectize v-model="selected3">
... options here ...
</select>
</div>
You can use your component in pretty much the way you want to use your directive:
<select2 name="selected1" id="selected1" v-model="selected">
<option disabled value="0">Select one</option>
<option value="1">Hello</option>
<option value="2">World</option>
</select2>
The name and id attributes get transferred to the underlying select element.
There is no (good) way to do this with a directive, which is an intentional design decision in Vue 2. There is no communication channel between a directive and the Vue as there is between a component and its parent component. A directive is not a sub-Vue, as a component is, it is a way of dealing with a small piece of the DOM in isolation.
I do not think there would be any particular advantage to writing this with a directive rather than a component.

Categories