VUE3父组件与模态框中子组件的传值

首先写一个模态框,我会一句句讲解这个的实现

第一句

<el-dialog v-model="dialogFormVisible1" :modal="false" draggable>
<ChildComponent :customer-list="customer_list" :reset-data="shouldResetData" @selected-customer="handleSelectedCustomer" />
<template #footer>
<span class="dialog-footer">
<el-button @click="noSure">取消</el-button>
<el-button type="primary" @click="onSure(), dialogFormVisible1 = false">确定</el-button>
</span>
</template>
</el-dialog>

el-dialog这是一个模态框,v-model="dialogFormVisible1"这是绑定一个是否打开模态框的属性

:modal="false"表示默认值是false是不打开的。draggable 属性设置为 true 表示该对话框 (el-dialog) 可以被拖动改变位置。具体来说,在 Element UI 中,draggable 属性用于启用对话框的拖拽功能,允许用户通过鼠标拖动对话框的标题栏来移动整个对话框的位置。这里默认是true

const dialogFormVisible1 = ref(false);

这个绑定的属性是这么定义的。

第二句,

 <ChildComponent   :customer-list="customer_list" :reset-data="shouldResetData"  @selected-customer="handleSelectedCustomer"  />

首先ChildComponent,这个是是随便你咋写的,他的来源是你导入的子组件

import ChildComponent from './CustomerInfoList.vue'; // 导入子组件

然后就是:customer-list="customer_list" :reset-data="shouldResetData",这是两个我传到子组件的参数,第一个是一个对象,第二个是一个状态,来控制我清不清除子组件的数据。这里这么传的两个东西我是这么定义的

const customer_list = reactive({
  Code: "",
  Name: "",
  ShortName: "",
  CustomerCategory: 0,
  Territory: 0,
  TradeCategory: 0,
  Effective: null,
  Saleser: "",
  TradeCurrency: 0,
  remarks: "",
  page: 1,
  // 每页显示条数
  limit: 10,
  // 总数据量
  total: 0,

});


const shouldResetData = ref(false); // 控制子组件数据重置

在子组件如此来接收

// 定义 Props
const props = defineProps({
  ItemList: {
    type: Object,
    required: true,
  },
  resetData: {
    type: Boolean,
    default: false,
  }
});

这样数据就从父组件传到子组件了。

@selected-customer="handleSelectedCustomer"这个函数用量监听子组件传递的数据,这样我就既可以传给子组件,也能收到子组件的返回,这个函数是这么写的

// 定义一个响应式的变量来暂存选中的客户数据
const selectedCustomer = ref(null);

//监听子组件传递的数据
function handleSelectedCustomer(customer) {
  selectedCustomer.value = customer;
}

子组件是这么传的

function handleSelectionChange(selectedRows: Array<Customer>) {
  // 更新 selectedRows 数组
  selectedRows.splice(0, selectedRows.length, ...selectedRows);
  if (selectedRows.length > 0) {
    // ElMessage.success(`选中了第 ${selectedRows[0].Id} 行 .`);
    //设置单行选中
    if (selectedRows.length > 1) {
      let del_row = selectedRows.shift();
      taskTableRef.value.toggleRowSelection(del_row, false);
      // 用于多选表格,切换某一行的选中状态,如果使用了第二个参数,则是设置这一行选中与否(selected 为 true 则选中)
      console.log('客户数据',props.customerList);
      console.log('重打数据',props.resetData);
    }
    // 触发事件,读入数组的第零项,父组件需监听这个事件
    emits('selected-customer', selectedRows[0]);
  }
}

这样父组件和子组件的相互传值就完成了!

有一点点启发麻烦点个关注,支持一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值