首页 > 解决方案 > Vue-multiselect在使用单选(对象)时防止选择任何项目

问题描述

我正在使用 Vue-multiselect 2.1.4

当我使用带有数组选项的单选时,它就像一个魅力。但是在对对象数组使用单选的情况下,所有项目都是绿色的并且它们是不可选择的!(他们有“被选中”类)

为了澄清问题,我使用了项目网站上的示例代码,并用我的数据替换了选项。

在此处输入图像描述

<multiselect v-model="value" deselect-label="Can't remove this value"
    track-by="name" label="name" placeholder="Select one"
    :options="options" :searchable="false" :allow-empty="false">
    <template slot="singleLabel" slot-scope="{ option }">
        <strong>{{ option.name }}</strong> is written in
        <strong>  {{ option.language }}</strong>
    </template>
</multiselect>

const config = {
    data() {
        return {
            value: null,
            options: []
        }
    },
    async mounted() {
        await this.getTerminals();
    },
    methods: {
        async getTerminals() {
            await window.axios.get("/api/Operation/GetTerminals")
                .then(resp => {
                    this.$data.options = resp.data;
                })
                .catch(err => {
                    console.error(err);
                });
            },
    }
};
const app = Vue.createApp(config);
app.component('Multiselect', VueformMultiselect);
app.mount('#app');

标签: vue.jsvue-multiselect

解决方案


如果是对象数组,首先您需要填充对象中的值,然后将对象推送到选项数组中。并且模板中的变化也很少。例如,如果您的对象是这样的,以下将起作用:

        data(){
    return{
     value: null,
     option: {
       value: "",
       name: "",
       icon: "",
     },
     options: [],
    }
    },

methods: {
getData(){
//call your service here
response.data.list.forEach((item, index) => {
            self.option.value = item.first_name + item.last_name;
            self.option.name = item.first_name + " " + item.last_name;
            self.option.icon =
              typeof item.avatar !== "undefined" && item.avatar != null
                ? item.avatar
                : this.$assetPath + "images/userpic-placeholder.svg";
            self.options.push({ ...self.option });
          });
}
}

然后在模板中填写如下选项:

            <Multiselect
                v-model="value"
                deselect-label="Can't remove this value"
                track-by="value"
                label="name"
                :options="options"
                :searchable="false"
                :allow-empty="false"
              >
                <template v-slot:singlelabel="{ value }">
                  <div class="multiselect-single-label">
                    <img class="character-label-icon" :src="value.icon" />
                    {{ value.name }}
                  </div>
                </template>

                <template v-slot:option="{ option }">
                  <img class="character-option-icon" :src="option.icon" />
                  {{ option.name }}
                </template>
              </Multiselect>

在创建的钩子中调用您的 getData() 函数。


推荐阅读