首页 > 解决方案 > 如何访问子组件的方法?

问题描述

我有一个子组件,它内置在父组件中。我想从父母那里访问孩子的方法。我想$refs用于这个目的。

模板:

<template>
  <div>Parent!</div>
</template>

脚本:

<script>
    Vue.component('child',{
      template: `<div>I am child</div>`,
    }
    export default {
       name: 'Parent'
    }
</script>

在这种情况下,我如何$refs为我的孩子申报?

标签: javascriptvue.js

解决方案


为此,您可以使用该ref属性为子组件分配一个引用 ID。

<template>
  <div>Parent!</div>
  <child ref="childComponent"/>
</template>

现在,您可以通过以下方式从父组件访问子组件实例:

this.$refs.childComponent // where componentName is the ref value

这也意味着您可以执行您在子组件下定义的方法。

this.$refs.childComponent.myFunction();

有关更多详细信息,请参阅文档


推荐阅读