vue3 父子组件调用

vue3 父子组件调用

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

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

vue 复制代码
// 父组件
<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>
vue 复制代码
// 子组件
<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

vue 复制代码
// 父组件
<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>
vue 复制代码
// 子组件
<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>
相关推荐
乱码三千17 分钟前
使用ComfyUI+MinMax-H3音视频模型生成视频
前端·后端·github
Coder_Ke20 分钟前
代码我都定位了,Codex 还在考古:于是我写了个 VS Code 插件
前端
LiaCode1 小时前
别让 AI 把仓库写成“代码平行宇宙”:从 Deslop 看生成前查重
前端·后端·github
nice先生的狂想曲2 小时前
javascript高级程序设计(六)——2026.9.5
前端·javascript
我爱写代码i2 小时前
SKAPP SK影视反编译详细教程+源码 含苹果端ipa
开发语言·javascript·ecmascript
光影少年2 小时前
如何做大型React+RN 项目架构设计、目录规范
前端·react native·react.js
一位正在转型AI全栈的前端工程师2 小时前
AI 全栈学习之旅 -Week 8:从单 Agent 到多 Agent 协作:LangGraph 实战与记忆持久化
前端·python
用户921080262862 小时前
Promise 和 async/await:从用途到执行机制
前端
yyt3630458412 小时前
KLineChartQuant:GLSL 的精度问题及 RTC 解法
前端·vue.js·react.js·交互·图形渲染·webgl·数据可视化
HarmonLTS2 小时前
智盾 WAF v8.2 Ultra|下一代 Web 应用防火墙
前端