父組件:
<template>
<div>
<div @click="openChild">彈彈彈,彈出子組件</div>
<childs ref="alert" @watchChild="parentReceive"></childs> <!--監聽子組件綁定的方法-->
</div>
</template>
<script>
import childs from '../components/modal/Alert'
export default{
data(){
return {
msg: '我是父組件的msg!!!'
}
},
components:{
childs
},
methods:{
parentReceive(message){
alert(message);
},
openChild(){
this.$refs.alert.open('我是子組件','子組件內容!!!!!');
}
}
}
</script>
<style>
</style>
子組件:
<template>
<modal :show='show' ref="modal">
<div slot="title">{{title}}</div>
<div slot="content">{{content}}</div>
<div slot="buttons" class="modal-buttons">
<span class="modal-button" @click="_onClick()">確定</span>
</div>
</modal>
</template>
<script>
import Modal from './Modal'
export default {
props: {
show: {
type: Boolean,
default: false
},
okText: {
type: String,
default: '確定'
},
},
data(){
return {
title: '',
content: ''
}
},
components: {
Modal
},
methods: {
open (title, content) {
this.title = title
this.content = content
this.$refs.modal.open()
},
close () {
this.title = ''
this.content = ''
this.$refs.modal.close()
},
_onClick(){
this.close();
this.$emit('watchChild','我是從子組件傳過來的內容!!!'); //觸發$emit綁定的watchChild方法
}
}
}
</script>
第一種方法:
如上:通過this.$emit()來觸發父組件的方法。具體就是子組件觸發$emit綁定的事件watchChild,然后父組件監聽watchChild,一旦watchChild被觸發便會觸發父組件的parentReceive方法。
父組件:
<template>
<div>
<div @click="openChild">彈彈彈,彈出子組件</div>
<childs ref="alert" :on-ok="parentReceive"></childs> <!--把父組件的方法名傳給子組件的onOK屬性-->
</div>
</template>
<script>
import childs from '../components/modal/Alert'
export default{
data(){
return {
msg: '我是父組件的msg!!!'
}
},
components:{
childs
},
methods:{
parentReceive(message){
alert(message);
},
openChild(){
this.$refs.alert.open('我是子組件','子組件內容!!!!!');
}
}
}
</script>
<style>
</style>
子組件:
<template>
<modal :show='show' ref="modal">
<div slot="title">{{title}}</div>
<div slot="content">{{content}}</div>
<div slot="buttons" class="modal-buttons">
<span class="modal-button" @click="_onClick()">確定</span>
</div>
</modal>
</template>
<script>
import Modal from './Modal'
export default {
props: {
show: {
type: Boolean,
default: false
},
okText: {
type: String,
default: '確定'
},
onOk: { //定義onOK屬性
type: Function
}
},
data(){
return {
title: '',
content: ''
}
},
components: {
Modal
},
methods: {
open (title, content) {
this.title = title
this.content = content
this.$refs.modal.open()
},
close () {
this.title = ''
this.content = ''
this.$refs.modal.close()
},
_onClick(){
this.close();
if(this.onOk){
this.onOk('我是子組件傳遞過來的數據!!!!');
}
}
}
}
</script>
第二種方法:
在子組件props中定義屬性onOK,類型為function,然后在父組件中把要觸發的方法名傳遞給onOK屬性,最后在子組件中判斷onOk是否存在,是的話直接執行這個方法。
效果:
---------------------
作者:yemuxia_sinian
來源:CSDN
原文:https://blog.csdn.net/yemuxia_sinian/article/details/80534296
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!