Vue父组件调用子组件方法

思考:

都知道Vue中子组件调用父组件的方法是只要将父组件方法传到子组件用props接收即可使用,可是父组件该怎么调用子组件呢?子组件方法创给父组件根本行不通。

解决思路:

通过用ref对组件进行唯一标识,用this.$refs.标识名 即可调用子组件方法(this.$refs.标识名 返回的是子组件对象)

  • 子组件
<template>
  <div>
       son components
  </div>
</template>

<script>
  export default {
    method:{
      fn(){
        console.log('You clicked the button.')
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>
  • 父组件
<template>
  <div>
    <button @click="fn">Please Click the</button>
    <SonComponent ref="SON"></SonComponent>
  </div>
</template>

<script>
  import SonComponent from './SonComponent'
  
  export default {
    components:{
      SonComponent
    },methods:{
      fn(){
        this.$ref.SON.fn()
      }
   }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

 

 

 

 

 

 

posted @ 2019-08-19 22:29  麦田的老哥  阅读(10)  评论(0)    收藏  举报