【问题标题】:Parent to Child interaction in VueVue 中的父子交互
【发布时间】:2019-04-08 13:16:58
【问题描述】:

我想知道如何在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()

【问题讨论】:

    标签: javascript vue.js components interaction


    【解决方案1】:

    您可以使用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'
        })
    }
    

    【讨论】:

      【解决方案2】:

      您可以将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

      【讨论】:

        【解决方案3】:

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

        父组件:

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

        一旦foo 的值发生变化,Vue 反应性就会发挥作用,它会通知/重新渲染子组件。

        子组件:

        现在,在这里,您可以观察道具的变化,一旦变为 true,您就可以调用函数/方法 (someFunction)。

        这里是fiddle,供您理解

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-21
          • 1970-01-01
          • 2011-12-23
          • 1970-01-01
          • 1970-01-01
          • 2016-11-07
          相关资源
          最近更新 更多