Search code examples
vue.jsvuejs3vue-options-api

V-If elements displaying regardless of condition resolving to false


The issue I am facing is that my v-if elements are displaying regardless of whether their value resolves to null, 'null', false, or falsy. Here is a minimal reproducible example: JS Fiddle

        <select id="city-select" multiple :disabled="citiesLoading" v-model="selectedCities">
          <option value="">Select cities</option>
          <option v-for="city in cities" :value="city.lID" :key="city.lID">
            {{ city.lCity }}<span v-if="city.lAdminName">, {{ city.lAdminName }}</span>
            <span v-if="city.lCapital">({{ city.lCapital }})</span>
          </option>
        </select>

The expected result in this Fiddle, is:

  • Guadeloupe selected:
  • "Pointe-à-Pitre, ()" should show as "Pointe-à-Pitre"
  • "Basse-Terre, (primary)" should show as "Basse-Terre (primary)"

I've intentionally made one of the fields null, and another an empty string, to show that both produce an unexpected outcome.

What could I be doing wrong here? The list of what I've tried so far is exhaustive, to the point I believe I must be overlooking something fundamental.


Solution

  • This is specific to how the application is rendered. Since in-DOM template is used, it needs to comply HTML specification. Nested element cannot exist inside option, and <span v-if="city.lAdminName"> is removed before it reaches template compiler.

    template element is an exception, it can exist inside elements with such restrictions such as option, tr, etc and is intended for template fragments both in HTML and Vue.

    It should be:

    {{ city.lCity }}<template v-if="city.lAdminName">, {{ city.lAdminName }}</template>