我定义了一个具有Child
组件的Parent
组件,这两个组件都具有动态转换,并将离开回调定义为outro
,问题是当组件被销毁时Parent
其outro
方法工作正常,但其Child
组件outro
方法永远不会被触发。有没有办法做到这一点并保持组件Child
可重用和解耦?演示。
应用模板:
<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,
},
})
请参阅更正的演示
-
使用
v-show
指令。查看比较 v-if 与 f-show<parent v-show="showContainer"></parent>
-
子元素需要自控制器和与属性绑定
-
在
<div class="Child"></div>
中添加v-if="showChild"
-
在
child
中创建props
道具:{ 显示儿童:{ 类型:布尔值, 默认值:真 } },
-
parent
中的绑定props
<child :showChild="showChild"></child>
很确定这种方式是不可能的。 即使使用 CSS 过渡,家长仍然需要控制孩子的过渡。 我们需要在过渡组件上有一个消失道具:p
也许你不会喜欢这个解决方案,但是,在父母的结尾,你可以打电话给this.$refs.child.outro(this.$refs.child.$el)