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>