How to pass values between parent and child components in Vue

Keywords: props, $emit(), bound data and events


foreword

`Hint: Here you can add the general content to be recorded in this article.
In projects, some commonly used public codes are often extracted and written as a subcomponent. Or if there are too many codes in one page, related codes can be extracted and written as subcomponents according to different functions, so that the code structure will be more concise and clear, and subsequent maintenance will be more convenient. This bit will be described with an example used in a project.


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

1. Introduce child components into parent components

Parent-child component page display: insert image description here
parent component imports child component related code:
insert image description here

Example: pandas is a NumPy-based tool created to solve data analysis tasks.

2. How to pass values ​​from the parent component to the child component

Parent component: passing data to child components through data binding

//父组件
<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;

3. How does the child component receive the value passed by the parent component and use (props)

1. Receive the passed value of the parent component through props

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

2. Assign the value of props to the array container in the child component to display the data passed from the parent component

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

4. How to pass values ​​from child components to parent components ($emit)

Subcomponent: Here, two click events are mainly used to cancel and confirm the subcomponent dialog box to pass values

   </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>

5. The parent component uses the value passed from the child component

As shown in the code below, closeData and confirmData respectively receive the values ​​passed by the subcomponents when canceling and confirming
insert image description here

Summarize

1. The parameter passing between parent and child components is more commonly used. When the parent component passes parameters to the child component, the child component uses props to receive the parameters, and the parent component binds the parameters to be passed.
2. When the child component passes parameters to the parent component, use $emit (the function of the parent component, the parameters to be passed) to pass the number to the parent component.

Guess you like

Origin blog.csdn.net/daishu_shu/article/details/124094774