phk
phk

Reputation: 2061

Vue.js - Empty results message with transition-group ("children must be keyed")

I have created little data filter tool using vue.js and I made it look fancy using transitions. But I also want to display a message if there are no results for the current filter setting, so I tried the following:

<transition-group …>

  <div class="SOME_CLASSES" v-for="x in RESULTS" :key="x.id">…</div>

  <div class="OTHER_CLASSES" v-if="!RESULTS">Sorry, no results.</div>

</transition-group>

…but this does not work and I am getting a warning:

[Vue warn]: children must be keyed:

Now I could move the message outside the <transition-group>:

<transition-group …>

  <div class="SOME_CLASSES" v-for="x in RESULTS" :key="x.id">…</div>

</transition-group>

<div class="OTHER_CLASSES" v-if="!RESULTS">Sorry, no results.</div>

…but then I would lose the fancy animation for when this message is displayed.

Is there some non-hacky solution to displaying the "empty results" message with a transition?
(A hacky solution would be creating a dummy entry in the RESULTS data and then checking for it everywhere.)

Upvotes: 0

Views: 1587

Answers (2)

wordbug
wordbug

Reputation: 671

<transition-group> is meant for lists; you need a <transition>. Transitioning single elements.

Keep the name property from the <transition-group> so that the animation is the same.

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should wrap the element that contains Sorry, no results. by a transition with same name as transition group as follows :

Vue.config.devtools = false;
Vue.config.productionTip = false;


new Vue({
  el: '#list-demo',
  data: {
    items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
    nextNum: 10
  },
  methods: {
    randomIndex: function() {
      return Math.floor(Math.random() * this.items.length)
    },
    add: function() {
      this.items.splice(this.randomIndex(), 0, this.nextNum++)
    },
    remove: function() {
      this.items.splice(this.randomIndex(), 1)
    },
  }
})
.list-item {
  display: inline-block;
  margin-right: 10px;
}

.list-enter-active,
.list-leave-active {
  transition: all 1s;
}

.list-enter,
.list-leave-to
/* .list-leave-active below version 2.1.8 */

{
  opacity: 0;
  transform: translateY(30px);
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="list-demo">
  <button class="btn btn-primary" v-on:click="add">Add</button>
  <button class="btn btn-primary" v-on:click="remove">Remove</button>
  <transition-group name="list" tag="p">
    <span v-for="item in items" v-bind:key="item" class="list-item">
      {{ item }}
    </span>
  </transition-group>

  <transition name="list">
    <div class="OTHER_CLASSES" v-if="items.length==0">Sorry, no results.</div>
  </transition>
</div>

Upvotes: 1

Related Questions