【问题标题】:How does <transition-group> work with Vue.components?<transition-group> 如何与 Vue.components 一起工作?
【发布时间】:2018-09-04 08:25:31
【问题描述】:

假设我想使用组件制作一个列表,如果我单击它就会消失,并使用transition-group 来做动画部分。

以下代码可以很好地执行:

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;
}

open1open2 在 Vue.js 的 data 中定义。

但是,下面的代码根本不会执行动画。

HTML:

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

CSS:同上

JavaScript:

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

所以问题是我如何为transition-group 中的组件设置动画。我已经搜索了几个小时,但没有找到与之相关的问题或文件。

更新:

关键问题是前一个例子中第一个句子消失后第二个句子平滑向上移动的动画在后一个例子中没有显示。虽然我可以把transition 放在template 里面,但这并不能解决问题。 我应该把整个transition-group写在template里面,还是别的什么...?

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    在使用 Vue 转换时,出于内部原因,转换/转换组组件必须与被切换的状态位于同一模板中。

    此外,Vue 组件要求组件始终只有一个根元素。 v-if 违反了这条规则,因为如果 v-if 恰好为假,它可能会导致元素不存在。

    要解决您的问题,请将转换移至 test-sth 组件。由于它管理自己的切换,它也应该管理自己的转换。

    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.

    【讨论】:

    • 抱歉问题描述不清楚,但实际问题是v-move部分的动画效果...我会尽快更新问题。
    猜你喜欢
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2021-12-14
    • 2021-04-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多