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>
相关推荐
小李子呢02111 小时前
前端八股CSS(2)---动画的实现方式
前端·javascript
GreenTea3 小时前
从 Claw-Code 看 AI 驱动的大型项目开发:2 人 + 10 个自治 Agent 如何产出 48K 行 Rust 代码
前端·人工智能·后端
渣渣xiong4 小时前
从零开始:前端转型AI agent直到就业第五天-第十一天
前端·人工智能
布局呆星4 小时前
Vue3 | 组件通信学习小结
前端·vue.js
C澒4 小时前
IntelliPro 企业级产研协作平台:前端智能生产模块设计与落地
前端·ai编程
OpenTiny社区5 小时前
重磅预告|OpenTiny 亮相 QCon 北京,共话生成式 UI 最新技术思考
前端·开源·ai编程
前端老实人灬5 小时前
web前端面试题
前端
Moment5 小时前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试
IT_陈寒5 小时前
为什么我的JavaScript异步回调总是乱序执行?
前端·人工智能·后端