2👍
✅
piggy-backing off of @husam’s answer
I would advise against using a selectedColor
value. You should use index (arrays) or key (objects) so you don’t end up duplicating data (in larger applications)
new Vue({
el: "#app",
data: {
colors: [
{color: 'Red'},
{color: 'Green'},
{color: 'Blue'}
],
colIndex: 0
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.6/dist/vue.min.js"></script>
<div id="app">
<select v-model="colIndex">
<option v-for="color, i in colors" :value="i">{{ color.color }}</option>
</select>
<div>{{ colors[colIndex].color }}</div>
</div>
You can also use a computed value
new Vue({
el: "#app",
data: {
colors: [
{color: 'Red'},
{color: 'Green'},
{color: 'Blue'}
],
colIndex: null
},
computed: {
selectedColor() {
return this.colors[this.colIndex] || {};
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.6/dist/vue.min.js"></script>
<div id="app">
<select v-model="colIndex">
<option v-for="color, i in colors" :value="i">{{ color.color }}</option>
</select>
<div>{{ selectedColor.color }}</div>
</div>
2👍
You can simplify things by using v-model
on the select
element to pick the value of the selected option and insert it into your div
.
new Vue({
el: "#app",
data: {
colors: [
{color: 'Red'},
{color: 'Green'},
{color: 'Blue'}
],
selectedColor: 'Red'
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.6/dist/vue.js"></script>
<div id="app">
<select v-model="selectedColor">
<option v-for="color in colors" :value="color.color">{{ color.color }}</option>
</select>
<div :style="{background: selectedColor}">{{ selectedColor }}</div>
</div>
Source:stackexchange.com