在 HTML 中选择中使用 Vue.js 和 Minimalect 显示默认值

Display a default value in HTML select using Vue.js and Minimalect

本文关键字:Minimalect 显示 js 默认值 HTML 选择 Vue      更新时间:2023-09-26

我正在使用Vue.js和Mininmalect HTML选择插件,按名称和值显示国家列表(值是2位国家代码)。

使用插件选择国家/地区时,我已经让它工作了。它将值添加到selected状态。

我无法弄清楚的是,当已经有一个处于状态时(即页面加载时从数据库中)如何显示值/国家/地区。

这是我所拥有的:

<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>

我正在努力使select属性出现,即 <option value="GB" selected>United Kingdom</option>,因此加载页面时有一个默认值。

您已经v-model="country"了,因此,如果您只是将 country 的值设置为数据库值,则选择将自动设置为该值。

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();
        }
    });
}

selected 更改v-model。我认为你的问题是性能问题。为函数添加setTimeout

<template>
    <select name="country" v-model="selected">
        <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;
            setTimeout(function(){
              $('select').minimalect({
                  onchange: function(value) {
                      vm.selected = value;
                  }
              });
            });
        }
    };
</script>