【问题标题】:How can I access the method of a child component?如何访问子组件的方法?
【发布时间】:2019-06-07 04:01:42
【问题描述】:

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

模板:

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

脚本:

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

在这种情况下,我如何为我的孩子声明$refs

【问题讨论】:

  • 你可以显示子方法以及你想如何在父组件中使用它?

标签: javascript vue.js


【解决方案1】:

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

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

现在您可以通过使用父组件来访问您的子组件实例:

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

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

this.$refs.childComponent.myFunction();

更多详情请见docs

【讨论】:

  • 另外,当刚接触 Vue 时,一个经典的问题是 refs 仅在 mounted hook 及之后可用。 (否则它们是未定义的)另外,如果 ref 在 v-if 中,您可能需要在更新的钩子中等待它。
  • 是的,当我试图访问 created() 钩子中子实例的属性时,我发现它会导致该错误。
猜你喜欢
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
相关资源
最近更新 更多