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>
相关推荐
知识分享小能手2 小时前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
demi_meng3 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
MC丶科3 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
千码君20164 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
lijun_xiao20095 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端
90后的晨仔6 小时前
Pinia 状态管理原理与实战全解析
前端·vue.js
杰克尼6 小时前
JavaWeb_p165部门管理
java·开发语言·前端
EndingCoder6 小时前
WebSocket实时通信:Socket.io
服务器·javascript·网络·websocket·网络协议·node.js
90后的晨仔6 小时前
Vue3 状态管理完全指南:从响应式 API 到 Pinia
前端·vue.js
90后的晨仔6 小时前
Vue 内置组件全解析:提升开发效率的五大神器
前端·vue.js