Vue 中的父子交互

Con*_*nor 1 javascript components interaction vue.js

我想知道如何在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>
Run Code Online (Sandbox Code Playgroud)

child.vue文件

<script>
    export default {
        methods: {
            someFunction() {
                alert('Success');
            }
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

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

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

Kap*_*emo 5

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

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

让你的父组件发送事件:

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

然后让你的子组件监听:

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