Vue中父子组件如何传值

关键词:props、$emit()、绑定的数据和事件


前言

`提示:这里可以添加本文要记录的大概内容
项目中往往会把一些常用的公共代码抽离出来,写成一个子组件。或者在一个页面中的代码太多,可以根据功能的不同抽离出相关代码写成子组件,这样代码结构会更加简洁明了,后续维护更加方便。本位将以一个项目中用到的例子进行描述哈


提示:以下是本篇文章正文内容,下面案例可供参考

一、将子组件引入父组件

父子组件页面展示情况:在这里插入图片描述
父组件引入子组件相关代码:
在这里插入图片描述

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

二、父组件如何传值给子组件

父组件:通过数据绑定将数据传递给子组件

//父组件
<device-dialog
      :personInfo="info" //父组件通过赋值给info将表单数据传给子组件
      :action="action" //判断是新增还是编辑 add、edit
      :dialogText="dialogText" //对话框显示的标题
      @toClose="dialogConfirm('cancel')" //关闭按钮对应的函数
      @toComfirm="requestApi('getUser')" //确定按钮对应的函数
      v-if="this.dialogFormNew" //控制对话框的显示与隐藏
></device-dialog>

this.info = this.form_user; //父组件中相关的值赋值给info
this.dialogText = '编辑设备信息';
this.dialogFormNew = true;

三、子组件如何接收父组件传过来的值并使用(props)

1.通过props接收父组件的传值

<script>
export default {
    
    
  name: 'personDetail',
  props: {
    
    
    personInfo: {
    
    
      type: Object,
      default: {
    
    }
    },
    action: {
    
    
      type: String,
      default: {
    
    }
    },
    dialogText: {
    
    
      type: String,
      default: {
    
    }
    }
  }
}
</script>

2.将props的值赋值给子组件里的数组容器从而展示父组件传过来的数据

created() {
    
    
    this.form_user = this.personInfo; //form_user是子组件对话框显示表单数据的数组
  }

四、子组件如何传值给父组件($emit)

子组件:这里主要通过子组件对话框取消和确定两个点击事件进行传值

   </template>
    </div>
     <el-dialog>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogConfirm('cancel')">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogConfirm('confirm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
   </div>
  </template>
  
<script>
dialogConfirm(res) {
    
    
if (this.action === 'edit') {
    
    
        if (res === 'cancel') {
    
    
          this.closeDialog();
        } else {
    
    
          this.$refs['userForm'].validate((valid) => {
    
    
            //验证成功
            if (valid) {
    
    
              this.requestApi('edit'); //进入api新增请求
            } else {
    
    
              //验证失败
              console.log('error submit!!');
              return false;
            }
          });
        }
      }
},
closeDialog() {
    
    
      this.$emit('toClose', false); //通过$emit将参数false传值给父组件toClose对应的函数
    },
requestApi(action, verifyCB) {
    
    
      switch (action) {
    
    
        // 查看编辑
        case 'edit':
        this.$axios({
    
    
            method: 'post',
            url: '/office/roomDevice/updateLock?random=' + Math.random() * 10,
            data: {
    
    
              id: this.form_user.deviceId,
              deviceName: this.form_user.deviceName,
              deviceAddress: this.form_user.deviceAddress
            },
            headers: {
    
    
              Authorization: 'Bearer ' + sessionStorage.getItem('token')
            }
          })
            .then((res) => {
    
    
              console.log('编辑_res:', res);
              if (res.data.code === 0) {
    
    
                this.tips(res.data.message, 'success');
                this.comfirm();
              } else {
    
    
                this.tips(res.data.message, 'warning');
              }
            })
            .catch((error) => {
    
    
              console.error(error);
            });
          break;
     },
     comfirm() {
    
    
      this.$emit('toComfirm'); //这里将相关的数据传回父组件
    }
</script>

五、父组件使用子组件传过来的值

如下面的代码所示,closeData和confirmData分别接收取消和确定时子组件传过来的值
在这里插入图片描述

总结

1、父子组件之间的传参用的比较多的就是当父组件向子组件传递参数时,子组件用props接收参数,父组件绑定要传的参数。
2、子组件传递参数给父组件时试用$emit(父组件函数,要传的参数)来传递数向父组件传递参数

猜你喜欢

转载自blog.csdn.net/daishu_shu/article/details/124094774