一、前言
在vue3中,当我们使用 <script setup> 语法糖时,组件默认不会自动暴露内部的任何状态或方法给外部使用,为了暴露某些属性或方法,实现特殊需求,则需要实现子组件暴露方法或属性给父组件。
二、父组件调用子组件方法/属性
子组件
- 子组件通过
defineExpose暴露方法 暴露属性用法仅供参考,常规场景下正常emit子传父即可
<template>
<uni-popup ref="popupRef" type="center" background-color="#fff"
border-radius="10px">
<view class="confirm-popup-title">提示</view>
<view class="confirm-popup-content">内容内容内容</view>
<view class="btns">
<view class="btns-cancel" @click="popupClose">取消</view>
<view class="btns-confirm" @click="confirm">确认</view>
</view>
</uni-popup>
</template>
<script setup>
import { ref,defineProps,defineExpose } from 'vue';
// 弹窗ref
const popupRef = ref(false);
const casualnessText = ref('子组件随意定义的内容');
// 弹出
function popupOpen() {
console.log('子弹出事件');
// popupRef.value.open()
}
// 取消
function popupClose() {
console.log('子取消事件');
// popupRef.value.close()
}
// 确认
function confirm() {
console.log('确认');
}
// 子组件暴露方法
defineExpose({
popupOpen,
popupClose,
casualnessText
})
</script>
父组件
- 父组件使用子组件的方法或属性
<template>
<button @click="submit">提交</button>
<ConfirmationBox ref="ConfirmationBoxRef"></ConfirmationBox>
</template>
<script setup>
import ConfirmationBox from '@/components/ConfirmationBox/index.vue';
import { ref } from 'vue';
const ConfirmationBoxRef = ref(null);
// 提交
function submit() {
console.log('-----提交----');
ConfirmationBoxRef.value.popupOpen();
console.log(ConfirmationBoxRef.value.casualnessText, '--------子组件---内容');
}
</script>
二、效果预览
- 执行效果如下