components/home.vue
<template>
<div >
<el-button @click="showDia" >显示</el-button>
<dialog-custom :dialogVisible="isShow" @close="closeDialog" ref="child1"></dialog-custom>
</div>
</template>
<script>
import cdialog from '@/components/count'
export default {
data(){
return{
isShow:false
}
},
components:{
'dialog-custom':cdialog
},
methods:{
showDia(){
this.isShow = true;
console.log(this.$refs.child1);
this.$refs.child1.alertdia();
},
closeDialog(){
this.isShow = false
},hh(){
console.log("parent")
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
components/count/index.vue
<template>
<div>
<el-dialog
title="自己封装的dialog"
@close="closeDialog"
:visible.sync="dialogVisible"
width="30%">
<span>这是一段自己封装的dialog</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
props: ["dialogVisible"],
methods: {
alertdia(){
console.log("this is son")
},
closeDialog() {
this.$emit("close");
this.$parent.hh();
}
}
};
</script>
总结:(结合上面的代码看)
1.父组件调用子组件的方法
<child-com ref="child"></child-com>
methods:{
getChildMethods(){
this.$refs.child.childmethod(); //childmethod 子组件中的方法
}
}
2.子组件调用父组件的方法
this.$emit("方法名");
this.$parents.方法名();
3.子组件调用父组件的值
data(){
props:[" "]
}
4.父组件调用子组件的值
通过子组件调用父组件的方法来传值
this.$emit("parentMethod",childData)
本文介绍了Vue中父子组件之间的通信方式,包括父组件如何调用子组件的方法(使用refs和$refs属性),子组件如何触发父组件方法(通过$emit事件)以及如何传递和获取数据。示例代码展示了具体的实现细节,包括自定义对话框组件的封装和使用。
1606

被折叠的 条评论
为什么被折叠?



