vue3 父子组件调用

vue3 父子组件调用

父组件调用子组件方法 子组件使用defineExpose将方法抛出

父组件定义 function,子组件通过 defineExpose 暴露方法,父组件通过 ref 获取子组件实例,然后通过 ref 获取子组件方法。

// 父组件
<template>
  <div>
    <el-button @click="handleClick">点击显示侧边抽屉</el-button>
    <ChildComponent ref="childRef" />
  </div>
</template>

<script setup lang="ts">
import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);

function handleClick() {
  let row = '这是父组件给子组件弹窗抽屉传递分参数';
  childRef.value.showDrawer(row);
}
</script>
// 子组件
<template>
  <div>
    <el-drawer v-model="drawerVisible" title="这是子组件" size="70%" class="drawer-class">
      <div>这是子组件 --- {{ parentRow }}</div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="">
const drawerVisible = ref(false);
const emit = defineEmits(['detail']);
const parentRow = ref('');
// 显示弹窗
const showDrawer = (row) => {
  drawerVisible.value = true;
  parentRow.value = row;
};
defineExpose({
  showDrawer,
});
</script>

子组件调用父组件方法 defineEmits

// 父组件
<template>
  <div>
    <el-button @click="handleClick">点击显示侧边抽屉</el-button>
    <ChildComponent ref="childRef" @childLoad="onLoad" />
  </div>
</template>

<script setup lang="ts" name="">
import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);
// 父组件调用子组件方法 --- 开始
function handleClick() {
  let row = '这是父组件给子组件弹窗抽屉传递分参数';
  childRef.value.showDrawer(row);
}
// 父组件调用子组件方法 --- 结束

// 子组件调用父组件方法 --- 开始
function onLoad(row) {
  console.log('通过子组件点击按钮,触发父组件方法,并传递参数', row);
}
// 子组件调用父组件方法 --- 结束
</script>
// 子组件
<template>
  <div>
    <el-drawer v-model="drawerVisible" title="这是子组件" size="70%" class="drawer-class">
      <div>这是子组件 --- {{ parentRow }}</div>
      <el-button type="success" @click="handleChildClick">点击按钮父组件会打印值</el-button>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="">
const drawerVisible = ref(false);
const parentRow = ref('');

// 父组件调用子组件方法 --- 开始
const showDrawer = (row) => {
  drawerVisible.value = true;
  parentRow.value = row;
};
defineExpose({
  showDrawer,
});
// 父组件调用子组件方法 --- 结束

// 子组件调用父组件方法 --- 开始
const emit = defineEmits(['childLoad']);
function handleChildClick() {
  emit('childLoad', '子组件加载完成');
}
// 子组件调用父组件方法 --- 结束
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值