Ad

Display A Default Value In HTML Select Using Vue.js And Minimalect

I'm using Vue.js with the Mininmalect HTML select plugin to display a list of countries by name and value (value being the 2 digit country code).

I've got it to work when using the plugin to select a country. It's adds the value to the selected state.

What I can't work out is how display a value/country when there is already one in state (i.e. from the database when the page loads).

This is what I have:

<template>
    <select name="country" v-model="country">
        <option v-for="country in countries" value="{{ country.value }}">{{ country.label }}</option>
    </select>
</template>

<script>
    export default {
        data() {
            return {
                selected: 'GB',
                countries: require('../utilities/countries.js'),
            }
        },
        ready() {
            var vm = this;
            $('select').minimalect({
                onchange: function(value) {
                    vm.selected = value;
                }
            });
        }
    };
</script>

I'm struggling to get the select attribute to appear, i.e. <option value="GB" selected>United Kingdom</option> so there is a default when the page is loaded.

Ad

Answer

You've got v-model="country", so if you just set the value of country to the database value, the select will automatically be set to that value.

data() {
    return {
        country: 'GB',
        countries: require('../utilities/countries.js'),
    }
},
ready() {
    var vm = this;
    $('select').minimalect({
        onchange: function(value) {
            vm.country = value;
        },
        afterinit: function() {
            $('select').val(vm.country).change();
        }
    });
}
Ad
source: stackoverflow.com
Ad