vue中父组件如何调用子组件中的方法

原文链接:https://www.jianshu.com/p/20c01b70eac3

  • 开发遇到一个问题:页面中有个对话框,对话框中有 取消确定两个按钮,这应该是 父组件中的内容,对话框中的表单是 通过子组件展示的,所以 点击父组件的内容需要调用子组件中的方法。
  • 解决办法:用 $ref 调用
// 子组件:
<template>
  <div>

  </div>
</template>

<script>
  export default {
    data(){
      return {
        num:'123'
      }
    },
    computed: {
    },
    components: {      
      'children': children
    },
    methods:{
      childMethod() {
        alert('childMethod do...')
      }
    },
    created(){
    }
  }
</script>

// 父组件: 在子组件中加上ref即可通过this.$refs.ref.method调用
<template>
  <div @click="parentMethod">
    <children ref="c1"></children>
  </div>
</template>

<script>
  import children from 'components/children/children.vue'
  export default {
    data(){
      return {
      }
    },
    computed: {
    },
    components: {      
      'children': children
    },
    methods:{
      parentMethod() {
        console.log(this.$refs.c1) //返回的是一个vue对象,所以可以直接调用其方法
        this.$refs.c1.childMethod(); 
      }
    },
    created(){
    }
  }
</script>

 

 



 

posted @ 2019-08-19 13:51  叶子0321~  阅读(210)  评论(0编辑  收藏  举报