Vue在子组件中调用方法的最佳实践

时间:2019-03-23 17:29:57

标签: vue.js

我已经阅读了很多有关此的文章,而且似乎有多种方法可以做到这一点,许多作者建议不要使用某些实现。

为简单起见,我创建了一个我想要实现的非常简单的版本。

我有一个父Vue, parent.vue 。它有一个按钮:

<template>
    <div>
        <button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
    </div>
</template>

在子Vue中, child.vue 我有一个带有函数的方法:

methods: {
    sayHello() {

        alert('hello');
   }
  }

当我单击父级中的按钮时,我想调用 sayHello() 函数。

我正在寻找实现这一目标的最佳实践方法。我看到的建议包括事件总线,子组件参考和道具等。

在我的方法中执行函数最简单的方法是什么?

抱歉,这确实非常简单,但我确实尝试进行一些研究。

谢谢!

4 个答案:

答案 0 :(得分:2)

一种简单的方法是执行此操作:

<!-- parent.vue -->
<template>
    <button @click="$refs.myChild.sayHello()">Click me</button>
    <child-component ref="myChild" />
</template>

只需为子组件创建一个ref,您就可以调用方法并访问其拥有的所有数据。

答案 1 :(得分:2)

您可以创建一个ref并访问方法,但是不建议这样做。您不应该依赖组件的内部结构。这样做的原因是您将紧密耦合组件,而创建组件的主要原因之一就是要松散耦合它们。

您应该依靠contract(某些框架/语言的界面)来实现这一目标。 contract中的Vue依赖于这样的事实:父母通过props与孩子进行通信,而children通过parentevents进行通信。

要在非父/子组件之间进行通信时,还有至少两种其他通信方法:

我现在将描述如何使用道具:

1。在子组件上定义

props: ['testProp'],
methods: {
 sayHello() {
    alert('hello');
 }
}

2。在父组件上定义触发数据

data () {
 return {
   trigger: 0
 }
}

3。在父组件上使用道具

<template>
 <div>
    <childComponent :testProp="trigger"/>
  </div>
</template>

4。观察子组件中的testProp并调用sayHello

watch: { 
    testProp: function(newVal, oldVal) {
      this.sayHello()
    }
}

5。从父组件更新trigger。确保始终更改trigger的值,否则watch不会触发。一种方法是增加触发器,或将其从真实值切换为虚假值(this.trigger =!this.trigger)

答案 2 :(得分:1)

我不确定这是最好的方法。但是我可以解释我能做什么... Codesandbox演示:https://codesandbox.io/s/q4xn40935w

从父组件发送prop数据msg。每当点击按钮切换button是/否

时,在父级msg
<template>
  <div class="parent">
    Button from Parent : 
    <button @click="msg = !msg">Say Hello</button><br/>
    <child :msg="msg"/>
  </div>
</template>

<script>
import child from "@/components/child";

export default {
  name: "parent",
  components: { child },
  data: () => ({
    msg: false
  })
};
</script>

在子组件watch中,道具数据为msg。每当msg更改触发一个方法。

 <template>
  <div class="child">I am Child Component</div>
</template>

<script>
export default {
  name: "child",
  props: ["msg"],
  watch: {
    msg() {
      this.sayHello();
    }
  },
  methods: {
    sayHello() {
      alert("hello");
    }
  }
};
</script>

答案 3 :(得分:-1)

一个简单的解决方案是使用来自 vanilla JS 的 custom events

在父组件中:

const customEvent = new CustomEvent('custom-event');
document.dispatchEvent(customEvent);

在子组件中:

document.addEventListener('custom-event', this.functionToCall);