vue封装组件 父子传值 (弹框实例)

本文介绍了Vue中父子组件之间的通信方式,包括父组件如何调用子组件的方法(使用refs和$refs属性),子组件如何触发父组件方法(通过$emit事件)以及如何传递和获取数据。示例代码展示了具体的实现细节,包括自定义对话框组件的封装和使用。

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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值