vue.js子組件呼叫/執行父組件function
callback function
by cactus77kiki
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="vapp">
<h3>Call Parent component function in Child component</h3>
<ele-example1></ele-example1>
</div>
<div id="uapp">
<h3>Call Parent function in Child component</h3>
<ele-child1 :callparent="dobyparent"></ele-child1>
</div>
JavaScript
/*
子組件呼叫/執行父組件function(CallBack Function)
ref1: https://wualnz.com/Vue-%E5%85%83%E4%BB%B6%E4%B9%8B%E9%96%93%E7%9A%84%E5%82%B3%E8%A9%B1%E7%AD%92-%E7%B8%BD%E6%95%B4%E7%90%86/
ref2: https://medium.com/js-dojo/passing-functions-as-props-an-anti-pattern-in-vue-js-b542fc0cf5d
*/
//子組件
Vue.component('ele-child1',{
template: `<div>
<button @click='execute'>call parent function</button>
</div>`,
props: {
callparent: {
type: Function
}
},
methods:{
execute: function(){
if(this.callparent){
//console.log('hi');
this.callparent();
}
}
}
});
//vue instance
var app2 = new Vue({
el: '#uapp',
methods:{
dobyparent: function(){
alert('hi this is from parent!');
}
}
});
//父組件
var app1 = new Vue({
el: '#vapp',
components: {
'ele-example1':{
template:`
<ele-child1 :callparent="dobyparent"></ele-child1>
`,
methods:{
dobyparent: function(){
alert("hi this is from parent component!");
}
}
}
}
});