Fork me on GitHub

vue之父子组件执行对方的方法

一、子组件执行父组件中的方法

1、父组件将方法名传给子组件,子组件进行调用

父组件中:

<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton> 
    methods: {
      addOneUser() {

        $('#addModal').modal('show')
      }
}

子组件中:

<template>

  <button class="btn" :class="currentBtn" @click="handleClickParent">

    <slot>按钮</slot>

  </button>

</template>
      props:{
        typeBtn:String,
        btnUserMethod:Function //验证类型接收父组件方法名
      },

     methods:{
        handleClickParent(){
          this.btnUserMethod(); //子组件调用父组件方法
        }
      },

2、子组件里用$emit向父组件触发一个事件,父组件监听这个事件

父组件中:

<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton> 
  methods: {
      addOneUser() {

        $('#addModal').modal('show')
      }
}

子组件中:

<template>

  <button class="btn" :class="currentBtn" @click="handleClickParent">

    <slot>按钮</slot>

  </button>

</template>
      methods:{
        handleClickParent(){
          this.$emit('addOneUser');  //这里还可以向父组件传参,只需要父组件函数有对应的形参即可
        }
      },
    }

二、父组件执行子组件中的方法

 子组件:

//子组件Vbutton 
childMethod(){
          alert("我是子组件方法")
        }

父组件:

<template>
 <div>
     <button @click="parentClick">点击</button>
        <Vbutton ref="child" />         <!--使用组件标签-->
</div>
</template>
      parentClick() {
        this.$refs.child.childMethod("我是子组件里面的方法"); // 调用子组件的方法childMethod
  },

(1)在子组件中写入相应的方法

(2)在父组件中引入子组件

(3) <Vbutton ref="mychild" /> 是在父组件中为子组件添加一个占位,ref="child"是子组件在父组件中的名字

(4)在父组件的方法中调用子组件的方法,很重要   this.$refs.child.childMethod("我是子组件里面的方法");

posted @ 2019-07-29 13:47  iveBoy  阅读(1919)  评论(0编辑  收藏  举报
TOP