Dynamically load options to chained select boxes from endpoint

Learn how to load chained select boxes using an endpoint.

String endpoints can contain variables using {elementPath|'default'} format. We can use this to achieve chained select boxes:

template
<template>
  <Vueform>
    <SelectElement
      name="country"
      label="Country"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/countries"
    />
    <SelectElement
      name="state"
      label="State/Province"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/states?country={country}"
    />
    <SelectElement
      name="region"
      label="County/Region"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/counties?country={country}&state={state}"
    />
  </Vueform>
</template>

The items that depend on an other element's value, will be refetched when the other element's value change. We can also reference complex elements (eg. lists or objects), in which case their value will be transformed to JSON and added to the url in an encoded format. If a value is already selected which is not among the newly fetched items, the value will be removed.

If we want to prevent fetching options until the parent has an options selected we can set resolveOnLoad to false and manually fetch options on @open event:

template
<template>
  <Vueform>
    <SelectElement
      name="country"
      label="Country"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/countries"
    />
    <SelectElement
      name="state"
      label="State/Province"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/states?country={country}"
      :resolve-on-load="false"
      @open="(el$) => {
        if (!el$.input.extendedOptions.length && el$.form$.el$('country').value) {
          el$.updateItems()
        }
      }"
    />
    <SelectElement
      name="region"
      label="County/Region"
      :search="true"
      input-type="search"
      autocomplete="off"
      items="/counties?country={country}&state={state}"
      :resolve-on-load="false"
      @open="(el$) => {
        if (!el$.input.extendedOptions.length && el$.form$.el$('state').value && el$.form$.el$('country').value) {
          el$.updateItems()
        }
      }"
    />
  </Vueform>
</template>

We can do the same for MultiselectElement and TagsElement.

  
👋 Hire Vueform team for form customizations and developmentLearn more