首页 > 解决方案 > Vuejs从父到子传递函数

问题描述

我有一个关于将功能从父母传递给孩子的初学者问题。在我的例子中,我想更多地使用孩子,有时它应该做其他事情v-on:focus。我怎样才能做到这一点?有一些选项可以用 prop 传递它,但我不知道怎么做,我认为这样做不好?也许使用 EventBus,如果是,那么如何?我想知道如何在 VueJs 中做到这一点的正确方法。

这是父组件:

import Child from "./child.js";
export default {
  name: "app",
  components: {
    Child
  },
  template: ` 
              <div>
                <child></child>
                <child></child>
                <child></child>
              </div>
            `
};

这是子组件:

export default {
  name: "test",
  template: `
              <div class="form-group">
                <div class="input-group">
                  <input v-on:focus="functionFromChild">
                  </div>
              </div>
            `,
  methods: {
    functionFromChild() {
      //run the function from parent
    }
  }
};

标签: vue.jsvuejs2vue-component

解决方案


您可以将函数作为任何其他道具传递

import Child from "./child.js";
 export default {
  name: "app",
  components: {
   Child
  },
  methods: {
   calledFromChild(id){
     console.log(id)
   }
  },
  template: ` 
          <div>
            <child :callback="calledFromChild" id="1"></child>
            <child :callback="calledFromChild" id="2"></child>
            <child :callback="calledFromChild" id="3"></child>
          </div>
        `
 };

然后在孩子

export default {
 name: "test",
 props: ["callback", "id"],
 template: `
          <div class="form-group">
            <div class="input-group">
              <input v-on:focus="() => this.calledFromChild(this.id)">
              </div>
          </div>
        `,
 }

我还为孩子添加了一个 ID,以便您知道哪个孩子正在拨打电话。

但这不是一个好主意。您应该使用从您的孩子发出的事件来发送一个事件,并从父母那里收听它。

在孩子

export default {
 name: "test",
 template: `
          <div class="form-group">
            <div class="input-group">
              <input v-on:focus="handleFocus">
              </div>
          </div>
        `,
  methods: {
   handleFocus() {
    this.$emit('focusEvent')
   }
  }
};

而在父母

<child @focusEvent="handleFocusFromChild"></child>

这里是一个工作示例


推荐阅读