简体   繁体   中英

How does <transition-group> work with Vue.components?

Suppose I want to use the components to make a list that would disappear if I click on it, and use the transition-group to do the animation part.

The following code can perform well:

HTML:

<transition-group name="testanim">
  <p key="1" v-if='open1' @click='open1 = false'>Can You See Me?</p>
  <p key="2" v-if='open2' @click='open2 = false'>Can You See Me?</p>
</transition-group>

CSS:

.testanim-enter-active, .testanim-leave-active {
  transition: all .5s;
}
.testanim-enter, .testanim-leave-to {
  transform: translateX(1rem);
  opacity: 0;
}
.testanim-leave-active {
  position: absolute;
}
.testanim-move {
  transition: all .5s;
}

open1 and open2 are defined in data in Vue.js.

However, the following code would not perform the animation at all.

HTML:

<transition-group name="testanim">
  <test-sth key="1"></test-sth>
  <test-sth key="2"></test-sth>
</transition-group>

CSS: the same with above

JavaScript:

Vue.component ("test-sth", {
  template: "<p v-if='open' @click='open = !open'>Can You See Me?</p>",
  data: function () {
    return {
      open: true,
    }
  }
})

So the problem is that how I can animate the components inside the transition-group . I've searched for a few hours but did not find some question or documents related to it.

Update:

The key problem is that the animation in the former example that the second sentence move upwards smoothly when the first sentense disappear do not show in the latter one. Although I may put the transition inside the template , That do not solve the problem. Should I write the whole transition-group inside the template , or something else...?

When using Vue transitions, for internal reasons, the transition/transition-group components must be in the same template as the state that's being toggled.

Also, Vue components require that there always be a single root element for a component. A v-if breaks this rule because it gives the possibility of the element not being there, if the v-if happens to be false.

To solve your issue, move the transitioning to the test-sth component. Since it manages its own toggling, it should manage its own transitioning as well.

Vue.component("test-sth", {
  template: `
    <transition name='testanim'>
      <p v-if='open' @click='open = !open'>Can You See Me?</p>
    </transition>
  `,
  data: () => ({
    open: true,
  }),
})

new Vue({
  el: "#app",
  template: `
    <div>
      <test-sth></test-sth>
      <test-sth></test-sth>
    </div>
  `,
})

See this fiddle for a working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM