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>
相关推荐
PieroPC几秒前
Nicegui 3.4.0 可以缩小组件之间的间距 label botton input textarea
前端
写代码的皮筏艇2 分钟前
数组 forEach
前端·javascript
running up43 分钟前
Vite 全面解析:特性、对比、实践及最新演进
javascript·typescript
.格子衫.1 小时前
JS原型链总结
开发语言·javascript·原型模式
shoubepatien1 小时前
JavaWeb_Web基础
java·开发语言·前端·数据库·intellij-idea
WordPress学习笔记1 小时前
wordpress外贸主题Google地图添加(替换)方案
前端·wordpress·wordpress地图
计算机毕设VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue旅游信息推荐系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·课程设计·旅游
OrangeForce1 小时前
Monknow新标签页数据导出
javascript·edge浏览器
小妖6661 小时前
力扣(LeetCode)- 93. 复原 IP 地址(JavaScript)
javascript·tcp/ip·leetcode
古月฿2 小时前
大学生素质测评系统设计与实现
java·vue.js·redis·mysql·spring·毕业设计