Search code examples
vue.jsantdantdv

Ant Design Vue Select Display Existing Items


Using Ant Design in Vue. In a Multi-select component, user is able to select and unselect associated objects. However, the existing tokens of preexisting associated objects should show the item.name, but instead show "undefined". It also does not show a checkmark next to existing objects in the select box. However, on submit, the "undefined" object is submitted correctly. New choices display within the select box correctly.enter image description here

Here is the element in the view:

<a-form-item :label="`${contact.name}'s Outlets`"
                   :wrapperCol="{lg: {span: 20}, sm: {span: 24} }">
        <a-select
            mode="multiple"
            v-model="contact.outlets"
            style="width: 100%"
            placeholder="Please select"
        >
          <a-select-option v-for="outlet in outlets" :key="outlet.name" :value="outlet.id">
            {{ outlet.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

Solution

  • As indicated in comments, you used an object element in contact.outlets[] for the initial value of the select. However, the a-select's value properties are bound to each element's id, so no match is found:

    <a-select-option
            v-for="outlet in outlets"
            :key="outlet.name"
            :value="outlet.id" 👈 option value is an `id`
    >
    

    Solution

    Instead of the object as initial value, use the object's id.

    Composition API
    export default {
      setup() {
        const outlets = reactive([
          { id: 1, name: 'Outlet A' },
          { id: 2, name: 'Outlet B' },
                👇
          { id: 3, name: 'Outlet C' },
        ]);                                                👇
        const contact = reactive({ name: 'John', outlets: [3] });
    
        return { outlets, contact };
      }
    }
    

    demo 1

    Options API
    export default {
      data() {
        const outlets = [
          { id: 1, name: 'Outlet A' },
          { id: 2, name: 'Outlet B' },
                👇
          { id: 3, name: 'Outlet C' },
        ];                                        👇
        const contact = { name: 'John', outlets: [3] };
    
        return { outlets, contact };
      }
    }
    

    demo 2