Reputation: 2738
I'm relatively new to Vue and using VueJS 2 latest build.
I'm getting a set of data from the database, something similar to this:
{
count: 3,
options: {
'red': 10,
'blue': 20,
'green': 30,
'yellow': 40
}
}
I want to create a number of select dropdowns based on the value of count
(in this case 3, but it could be any number).
In each select dropdown I want to display the options
and adding v-model to them (and to Vue's data
object) dynamically based on how many select boxes we have to create.
Here is my attempt, but it doesn't work, because I don't know where/how to bind the v-model dynamically.
<template>
<div>
<select v-for="(c, index) in count" v-model="models[index]" :key="index">
<option v-for="(option, index) in options" :key="index">
{{ option }}
</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
count: 3,
options: {
red: 10,
blue: 20,
green: 30,
yellow: 40,
},
models: []
}
},
}
</script>
What is the best way to bind the values to data with v-models dynamically? If you need anything else, just let me know.
Upvotes: 0
Views: 504
Reputation: 450
You can achieve that using components...
create a component called: dropdown.vue //anything you wan to name it
//dropdown.vue
<template>
<div>
<select :key="index" @change="emitChange">
<option v-for="(option, index) in options" :key="index">
{{ option }}
</option>
</select>
</div>
</template>
<script>
export default {
name: 'Dropdown',
model: {
prop: 'value',
event: 'change'
},
props: {
value: String
},
//props: ['options', 'key'],
/*data() {
selectValue: "", //option selected value
}, */
methods: {
emitChange() {
this.$emit('change', $event.target.value)
}
}
}
</script>
Now in your child you can: Edit: Now your components is like a select box with custom v-model
<template>
<template v-for="(c, index) in count">
<Dropdown v-model="selectedOption" :index="index" :items="options" />
</template>
</template>
<script>
import Dropdown from 'path/to/components/dropdown'
export default {
data() {
return {
selectedOption: "",
count: 3,
options: {
red: 10,
blue: 20,
green: 30,
yellow: 40,
},
}
},
}
</script>
Now you can perform action with the v-model in the components...
Edit: I have modified the components to acts as dropdown with custom v-model.
Upvotes: 1