如何从vue.js中的父级访问子方法 [英] How to access to a child method from the parent in vue.js

查看:102
本文介绍了如何从vue.js中的父级访问子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two nested components, what is the proper way to access to the child methods from the parent ?

this。$ children [ 0] .myMethod()似乎可以做到这一点,但它非常难看,不是吗,有什么更好的方法:

this.$children[0].myMethod() seems to do the trick but it is pretty ugly, isn't it, what can be better way:

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

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


推荐答案

VueJS中的亲子沟通



鉴于所有后代都可以通过这个。$ root 访问根Vue实例,父组件可以通过<$访问子组件c $ c> this。$ children 数组,子组件可以通过这个。$ parent 访问它的父级,你的第一直觉可能是直接访问这些组件。

Parent-Child communication in VueJS

Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

VueJS文档特别警告这两个原因:

The VueJS documentation warns against this specifically for two very good reasons:


  • 它将父母与孩子紧密联系在一起(反之亦然)

  • 你不能依赖父母的状态,因为它可以被修改为
    by一个子组件。

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

The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:


  1. $ on() - 允许您在Vue实例上声明侦听事件的侦听器

  2. $ emit() - 允许您在同一个实例上触发事件(自我)

  1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
  2. $emit() - allows you to trigger events on the same instance (self)



使用 $ on()的示例 $ emit()



Example using $on() and $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中组件之间的通信

Answer taken from the original post: Communicating between components in VueJS

这篇关于如何从vue.js中的父级访问子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆