一、子組件執行父組件中的方法
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("我是子組件里面的方法");