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

JavaScript

樱A

2020-03-10

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

this.$children[0].myMethod() 似乎可以解决问题,但这很难看,不是,有什么更好的方法:

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

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

第498篇《如何在vue.js中从父级访问子级方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
橙ぺo痕 2020.03.10

为了将一个子组件与另一个子组件进行通信,我在父对象中创建了一个方法,该方法通过以下方式在子对象中调用方法:

this.refs.childMethod()

从另一个孩子那里,我调用了root方法:

this.$root.theRootMethod()

它为我工作。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android