Vue 子组件离开转换回​​调不起作用

Vue child component leave transition callback not working

我定义了一个 Parent 组件,它有一个 Child 组件,两个组件都有动态转换,离开回调定义为 outro,问题是当 Parent组件被销毁它的 outro 方法工作正常但它的 Child 组件 outro 方法永远不会被触发。有没有办法做到这一点并保持 Child 组件可重用和解耦? Demo.

应用模板:

<div id="app">
  <parent v-if="showContainer"></parent>
  <button @click="showContainer = !showContainer">
    Toggle Container
  </button>
</div>

Javascript:

// ISSUE:
// 1. Parent removes child component in its `outro` method
// 2. Child `outro` method never gets called

var Child = {
    template: `
    <transition
        :css="false"
        appear
        @appear="intro"
        @enter="intro"
        @leave="outro"
    >
        <div class="Child"></div>
    </transition>`,
    methods: {
        intro: function (el, done) {
            TweenLite.fromTo(el, 0.5,
                { y: '100%' },
                { y: '0%', delay: 0.5, onComplete: done })
        },
        outro: function (el, done) {
            // 2 <===
            TweenLite.to(el, 0.5,
                { y: '100%', onComplete: done })
        },
    },
}

var Parent = {
    template: `
    <transition
        :css="false"
        appear
        @appear="intro"
        @enter="intro"
        @leave="outro"
    >
        <div class="Parent">
            <div ref="inner" class="Parent__inner"></div>
            <child v-if="showChild"></child>
        </div>
    </transition>`,
    components: {
        Child: Child,
    },
    data() {
        return {
            showChild: true,
        }
    },
    methods: {
        intro: function (el, done) {
            TweenLite.fromTo(this.$refs.inner, 0.5,
                { y: '100%' },
                { y: '0%', delay: 0.25, onComplete: done })
        },
        outro: function (el, done) {
            // 1 <===
            // Setting `showChild` to `false` should remove Child component
            // and trigger its `outro` method ¿?
            this.showChild = false
            TweenLite.to(this.$refs.inner, 0.5,
                { y: '100%', delay: 0.25, onComplete: done })
        },
    },
}

new Vue({
    el: '#app',
    data() {
        return {
            showContainer: true,
        }
    },
    components: {
        Parent: Parent,
    },
})

很确定这是不可能的。 即使使用 CSS 转换,parent 仍然需要控制 child 的转换。 我们需要在 Transition 组件上使用 disappear 道具 :p

也许您不会喜欢这个解决方案,但是在 parent 的结尾,您可以调用 this.$refs.child.outro(this.$refs.child.$el)

查看更正 demo

  1. 使用v-show指令。见比较 v-if vs f-show

    <parent v-show="showContainer"></parent>
    
  2. 子元素需要自己控制并绑定属性

    • <div class="Child"></div>

    • 中添加v-if="showChild"
    • child

    • 中创建 props

    props: { showChild: { type: Boolean, default: true } },

    • parent
    • 中绑定 props
    <child :showChild="showChild"></child>