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

Vue中如何将API获取的变体名称渲染到下拉框并实现选中展示对应价格

问题根因

你给Dropdown组件传递的options参数格式错误:product.attributes.variations是包含多个变体对象的数组,直接使用.name无法批量获取所有子项的name字段,你写的[product.attributes.variations.name]最终得到的是[undefined],所以下拉框没有内容。

同时如果你后续需要根据选中项获取对应价格,不建议只提取name数组传递,直接传完整的variations数组、调整下拉组件的显示逻辑会更方便。


解决方法

方案1:仅展示name(不支持后续取价格)

直接用数组map方法提取所有变体的name字段作为选项列表:

<Dropdown
  :options="product.attributes.variations.map(item => item.name)"
  :default="'Choose an option'"
  class="select"
/>

方案2(推荐):传完整变体对象,支持后续取价格

  1. 父组件调用Dropdown时传入完整variations数组,用v-model接收选中的变体对象:
<Dropdown
  :options="product.attributes.variations"
  :default="'请选择选项'"
  class="select"
  v-model="selectedVariation"
/>
<!-- 选中后展示对应价格 -->
<p v-if="selectedVariation">价格(不含税):{{ selectedVariation.price_excl_vat }}</p>
  1. 调整Dropdown组件的模板,适配对象类型的选项:
<template>
    <div class="custom-select" :tabindex="tabindex" @blur="open = false">
        <div class="selected" :class="{ open: open }" @click="open = !open">
            <!-- 默认提示是字符串直接展示,选中变体后展示name -->
            {{ typeof selected === 'string' ? selected : selected.name }}
        </div>
        <div class="items" :class="{ selectHide: !open }">
            <div
                v-for="(option, i) of options"
                :key="i"
                @click="
          selected = option;
          open = false;
          $emit('input', option);
        "
            >
                <!-- 选项展示变体name -->
                {{ option.name }}
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        options: {
            type: Array,
            required: true,
        },
        default: {
            type: String,
            required: false,
            default: null,
        },
        tabindex: {
            type: Number,
            required: false,
            default: 0,
        },
    },
    data() {
        return {
            // 优先展示默认提示,不要自动取第一个对象避免显示异常
            selected: this.default || null,
            open: false,
        };
    },
    mounted() {
        this.$emit("input", this.selected);
    },
};
</script>

内容的提问来源于stack exchange,提问作者magic bean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:15:04