Vue 中的父子交互

Parent to Child interaction in Vue

我想知道如何在Vue中进行亲子交互

举个小例子来说明一下。

parent.vue 文件

<template>
    <div>
        <input @input="validate" type="text" />
        <child-component></child-component>
    </div>
</template>

<script>
    export default {
        methods: {
            validate(event) {
                if (event.target.value == 'hello') {
                    // make my child component to do something
                }
            }
        }
    }
</script>

child.vue 文件

<script>
    export default {
        methods: {
            someFunction() {
                alert('Success');
            }
        }
    }
</script>

注意:这只是一个例子。我的实际情况有点复杂这里就不解释了

在这个例子中,我想知道当父组件中的if条件为真时,如何触发子组件中的函数someFunction()

您可以将 ref 分配给您的子组件,然后使用 $refs 直接调用子组件上的方法。

<template>
    <div>
        <input @input="validate" type="text" />
        <child-component ref="child"></child-component>
    </div>
</template>

<script>
    export default {
        methods: {
            validate(event) {
                if (event.target.value == 'hello') {
                    this.$refs.child.someFunction();
                }
            }
        }
    }
</script>

Vue Docs Ref

简短回答:您可以为此目的使用 propswatch/computed 属性。

父组件:

根据您的情况,您可以将 foo 定义为父组件中的 data 属性 并使用 v-modelfoo 绑定到输入元素(推荐方式) 保持它与你已经完成的相同(监听输入事件)并且一次,它等于某个值hello(在您的情况下)它将 foo 更改为 true。

一旦 foo 值发生变化,Vue 反应性就会发挥作用,它 informs/re-renders 子组件。

子组件:

现在,在这里,你可以观察道具的变化,一旦它变成true你就可以调用function/method(someFunction).

这里fiddle供大家理解

您可以使用 vue event bus 来触发来自不同组件的事件。

首先,在您的 main.js 文件中初始化 Vue.prototype.$bus = new Vue();

让您的父组件发送事件:

validate(event) {
    if (event.target.value == 'hello') {
        this.$bus.$emit('throw', 'Hi')
    }
}

然后让你的子组件监听:

created() {
    this.$bus.$on('throw', ($event) => {
        console.log($event)  //shows 'Hi'
    })
}