vue3 <script setup> 父组件调用子组件方法

980 阅读1分钟

场景

vue3 使用<script setup>语法糖实现父组件调用子组件方法。项目场景子组件弹窗表单,父组件提交接口在成功回调里关闭子组件的弹窗。

父组件

// 父组件
<template>
    <div> 
        <childDialog ref="childRef"/>
        <button @click="onClose">关闭</button>
    </div>
</template>

<script setup>
import { ref } from "vue";
import childDialog from "./childDialog.vue";
const childRef = ref(null);
const onClose = () => {
    // childRef.value.dialogVisible = false;
    childRef.value.onCancelVisible()
}
</script>

子组件

<template>
  <el-dialog v-model="dialogVisible" title="测试" width="30%">
   <div>我是子组件form表单</div>
   <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onSubmit()"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from "vue";
const dialogVisible = ref(true);
const onCancelVisible = () => {
     dialogVisible.value = true;
}

const onSubmit = () => {
   // do something   e.g: emit('onParentFn',formData) 
}
// 暴露方法父组件调用子组件方法或者属性
defineExpose({
  // dialogVisible,
  onCancelVisible,
});
</script>

这里主要是用到[defineExpose]将属性从子组件暴露出去。官方文档defineExpose

image.png

使用defineComponent写法如下:

父组件

// 父组件
<template>
    <div> 
        <childDialog ref="childRef"/>
        <button @click="onClose">关闭</button>
    </div>
</template>

<script> 
import { defineComponent, ref, } from 'vue';
import childDialog from "./childDialog.vue";
export default defineComponent({ 
    setup(){
        const childRef = ref(null);
        const onClose = () => {
            // childRef.value.dialogVisible = false;
            childRef.value.onCancelVisible()
        }
    }
    return {
        childRef,
        onClose
    }
})
</script>

子组件

<template>
  <el-dialog v-model="dialogVisible" title="测试" width="30%">
   <div>我是子组件form表单</div>
   <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onSubmit()"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script> 
import { defineComponent, ref, } from 'vue';
export default defineComponent({
    setup(){
        const dialogVisible = ref(true);
        const onCancelVisible = () => {
             dialogVisible.value = true;
        }
        const onSubmit = () => {
           // do something   e.g: emit('onParentFn',formData) 
        }
    }
    return{
      dialogVisible,
      onSubmit,
      onCancelVisible
    };
})
</script>