DanVeira DanVeira - 10 days ago 7
HTML Question

How to trigger Vue event when selecting an option from select list

JSFiddle: https://jsfiddle.net/qc7yqvvs/

It works when I use the mouse to click on an option, but if I use the arrow keys to navigate the options it won't update the

multiplier
. The guide only has the
:click
event, I tried with
:select
,
:enter
and others but they don't seem to exist.

Answer

The event you are probably after is v-on:change or shorthand: @change. You'd then set this on the select rather than the options.

However you'll probably find it easier to do this by changing the multiplier to an object and then using the intervals value to select the corresponding one, i.e.

EDIT

Following your comments I see it may be tricky to build objects within the component so you'd rather set them in the html. To do so try binding the value of each option and then setting an object instead on the v-model, i.e.

Vue.component('my-component', {
    data: function() {
        return {
            value: {},
        }
    },
    computed: {
        total: function() {
            return this.value.interval ? (this.value.interval * this.value.multiplier).toFixed(2) : 0
        }
    }
});

const app = new Vue({
    el: '#app',
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
    <my-component inline-template>
        <div>
            <select size="6" v-model="value">
                <option :value="{ interval: 24, multiplier: 1 }">24</option>
                <option :value="{ interval: 12, multiplier: 0.71 }">12</option>
                <option :value="{ interval: 8, multiplier: 0.56 }">8</option>
                <option :value="{ interval: 4, multiplier: 0.47 }">4</option>
                <option :value="{ interval: 2, multiplier: 0.25 }">2</option>
                <option :value="{ interval: 1, multiplier: 0.12 }">1</option>
            </select>
            <p>
                value: {{ value }}
            </p>
            <p>
                Total: {{ total }}
            </p>
        </div>
    </my-component>
</div>