You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vue-multiselect 3.0.0 beta1插槽模板无法工作,求解决方案

vue-multiselect 3.0.0-beta.1 插槽模板无法正常工作的解决方案

我成功实现过,你的代码里有两个关键问题导致插槽不生效:

问题1:插槽语法混用错误

Vue3已废弃slot和slot-scope属性,必须使用纯Vue3的v-slot语法(或缩写#),不能混用旧属性与新语法。

问题2:插槽参数解构错误

vue-multiselect 3.x的插槽(如singleLabel、option)传递的是包含option对象的上下文,需先获取option再访问其属性,而非直接解构name/last。

正确实现代码

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vue-multiselect@3.0.0-beta.1/dist/vue-multiselect.esm.css" />
<style>
    [v-cloak] {
        display: none;
    }
</style>
<script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3.2.45/dist/vue.esm-browser.prod.js",
        "vue_multiselect": "https://cdn.jsdelivr.net/npm/vue-multiselect@3.0.0-beta.1/dist/vue-multiselect.esm.min.js"
      }
    }
</script>
<script type="module">
    import { createApp } from 'vue'
    import VueMultiselect from "vue_multiselect";

    const app = createApp({
        data() {
            return {
                value: null,
                options: [
                    { name: "John", last: "Smith" }, 
                    { name: "Bob", last: "Chair" }, 
                    {name:"Chuck",last:"Norris"}
                ]
            }
        },
        components: {
            VueMultiselect
        }
    }).mount('#app');
</script>
<div id="app" v-cloak>
    <VueMultiselect
                    v-model="value"
                    placeholder="开始输入查找地址"
                    open-direction="bottom"
                    :options="options"
                    :options-limit="100"
                    :limit="20"
                    :searchable="true"
                    :hide-selected="false"
                    :close-on-select="true"
                    :clear-on-select="false"
                    :multiple="false"
                    :internal-search="true"
                    :max-height="300"
                    :show-no-results="false"
                    :preserve-search="false"
                    :allow-empty="true"
                    :reset-after="false">
        <!-- 使用Vue3的v-slot语法,通过option参数访问数据 -->
        <template #singleLabel="{ option }">
            <span>{{ option.name }}</span>
        </template>
        <template #option="{ option }">
            <b>{{ option.name }}</b>
            <br />
            <span>{{ option.last }}</span>
        </template>
    </VueMultiselect>
</div>

关键修改点

  • 移除旧的slot属性,改用#singleLabel和#option(v-slot:的缩写形式)
  • 插槽参数正确解构出option对象,再访问其name/last属性
  • 组件注册名称改为VueMultiselect,使用时标签名保持一致(非必须,但更规范)

修改后插槽即可正常渲染自定义内容。

内容的提问来源于stack exchange,提问作者Donny V.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:14:54