如何在 vue 中从父方法访问子方法.js

2022-08-30 03:08:16

我有两个嵌套组件,从父级访问子方法的正确方法是什么?

this.$children[0].myMethod()似乎做了这个把戏,但它很丑陋,不是吗,有什么更好的方法:

<script>
import child from './my-child'

export default {
  components: {
   child
  },
  mounted () {
    this.$children[0].myMethod()
  }
}
</script>

答案 1

您可以使用引用

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

如果您不喜欢紧密耦合,则可以使用事件总线,如@Yosvel Quintero 所示。下面是使用事件总线的另一个示例,方法是将总线作为道具传入。

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

组件的代码。

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/


答案 2

VueJS 中的亲子沟通

假设所有后代都可以通过 访问一个 root Vue 实例,父组件可以通过数组访问子组件,而子组件可以通过 访问它的父组件,你的第一本能可能是直接访问这些组件。this.$rootthis.$childrenthis.$parent

VueJS文档特别警告这一点,原因有两个:

  • 它将父母与孩子紧密耦合(反之亦然)
  • 您不能依赖父级的状态,因为子组件可以对其进行修改。

解决方案是使用 Vue 的自定义事件接口

Vue 实现的事件接口允许您在组件树上下通信。利用自定义事件接口,您可以访问四种方法:

  1. $on()- 允许您在 Vue 实例上声明一个监听器来监听事件
  2. $emit()- 允许您在同一实例(自身)上触发事件

示例使用和:$on()$emit()

const events = new Vue({}),
    parentComponent = new Vue({
      el: '#parent',
      ready() {
        events.$on('eventGreet', () => {
          this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;
        });
      },
      data: {
        parentMsg: 'I am listening for an event..',
        counter: 0
      }
    }),
    childComponent = new Vue({
      el: '#child',
      methods: {
      greet: function () {
        events.$emit('eventGreet');
        this.childMsg = `I am firing greeting event ${++this.counter} times..`;
      }
    },
    data: {
      childMsg: 'I am getting ready to fire an event.',
      counter: 0
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>

<div id="parent">
  <h2>Parent Component</h2>
  <p>{{parentMsg}}</p>
</div>

<div id="child">
  <h2>Child Component</h2>
  <p>{{childMsg}}</p>
  <button v-on:click="greet">Greet</button>
</div>

答案摘自原始帖子:VueJS中的组件之间的通信