如何在Vue js中从父组件添加子组件的方法? [重复]

问题描述 投票:-1回答:1

我正在尝试从父组件调用子组件的方法(在子组件中定义),我不确定该怎么做。

在Vue中可能吗?

vue.js vuejs2 vue-component vuex
1个回答
1
投票

在vue文档中有充分的记录

https://vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

示例:

// child component
<template>
 ...
</template>

<script>
export default {
  name: 'ChildComponent',
  methods: {
    someChildMethod() {}
  },
}
</script>
// parent component
<template>
 <child-component ref="child"/>
</template>

<script>
export default {
  name: 'ParentComponent',
  components: {
    ChildComponent: () => import('child_component_path')
  },
  methods: {
    callChildMethod() {
      this.$refs.child.someChildMethod();
    }
  },
}
</script>

ParentComponent可以使用this。$ refs.child访问ChildComponent。

要从ParentComponent运行someChildMethod(),请运行this。$ refs.child.someChildMethod()

© www.soinside.com 2019 - 2024. All rights reserved.