首页 文章

当组件从父组件动态更改时,在子组件中调用方法

提问于
浏览
1

我有一个简单的组件层次结构,其中有一个父组件,它包含以下模板 <div><component :is="current"></component></div> 和两个子组件,它们是动态'switched' out,通过 current 的值 .

'switching'组件的逻辑正在父组件中处理 . 但是,当我尝试在第二个子组件中执行一个方法时(响应从第一个子组件发出的事件,在父组件中被侦听,并在父组件中更改 current 的值),通过 mounted 生命周期钩子,没有观察到预期的结果 .

本质上,当组件作为父组件中的当前组件“切换”时,我找不到一种调用子组件方法的好方法 .

我实际上已经考虑过在实例上使用 $refs$children 属性,但这些似乎没有任何帮助 . 我还推理使用事件系统 . 我通常在 mounted 生命周期钩子中'define'是一个事件监听器,但是,我指的是使用生命周期钩子的'issue'

这种情况的常用方法是什么?

1 回答

  • 2

    对于作为“当前”子组件调用方法的子组件,有两种选择立即浮现在脑海中:

    1)使用 mounted 生命周期钩子 . 为了使其正常工作,您必须使用 v-if 才能有条件地显示子组件,否则子组件将不会触发 mounted 生命周期钩子 . 否则,如果您使用 v-show 或某些其他机制有条件地显示子组件, mounted 挂钩将只触发一次 .

    2)使用监视属性 . 代替上述内容,您可以执行以下操作:

    <child-component :target_prop="current"></child-component>
    
    Vue.component('child-component', {
        . . .,
        props: ['target_prop'],
        watch: {
            target_prop: function() {
                if(this.target_prop == your_expected_value) {
                    //execute the desired method for this component
                }
            }
        }
    });
    

    当然,这只是一个概念验证示例,并且有很多替代方法可以使用受监视的属性 .

    我也听说过使用“总线”来处理组件间通信,但我不相信它会比上面两种解决方案更好(并且可能更糟) .

    就个人而言,我更喜欢 mounted 生命周期钩子方法,尽管's the caveat that any 643558 or data in your child components will be lost on switching between them (although you could also emit a settings object on destruction and store/restore those settings as needed, but that could get messy). You'll必须最终判断哪种方法更适合您的需求以及您更适合处理的后果 .

相关问题