se
2 years ago
40
3
Vue

Make whole template in single-file component conditional without superfluous HTML element

Posted 2 years ago by se

foo is set via AJAX, so the following (very simplified) template causes the expected Cannot read property type error.

<template>
  <div>{{ foo.bar }}</div>
  <div>{{ foo.baz }}</div>
</template>

I'd like to make the whole template conditional on foo being set, so I tried the following.

<!-- Doesn't work, maybe the outermost template is special -->
<template v-if="foo">
  <div>{{ foo.bar }}</div>
  <div>{{ foo.baz }}</div>
</template>

<!-- Doesn't work either, nothing is displayed -->
<template>
  <template v-if="foo">
    <div>{{ foo.bar }}</div>
    <div>{{ foo.baz }}</div>
  </template>
</template>

<!-- Only the first div is displayed? -->
<template>
  <div v-if="foo">{{ foo.bar }}</div>
  <div v-if="foo">{{ foo.baz }}</div>
</template>

So I settled for the following.

<template>
  <div v-if="foo">
    <div>{{ foo.bar }}</div>
    <div>{{ foo.baz }}</div>
  </div>
</template>

Is there any way that works without the superfluous div?

Please sign in or create an account to participate in this conversation.