Vue3.x 父组件Setup、Ref操纵子组件中的元素&方法

本文介绍了在Vue3中如何通过`defineComponent`和`setup`语法糖实现父子组件间的通信。针对使用`ref`操纵DOM时遇到的问题,提供了两种解决方案。在`defineComponent`中,需要将子组件的方法返回;而在`setup`中,则需使用`defineExpose`将方法暴露给父组件。这两个方法帮助开发者更好地理解和掌握Vue3中的组件通信机制。
摘要由CSDN通过智能技术生成


小伙伴们在开箱Vue3的过程中一点会踩到不少坑。

比如很多小伙伴想要通过ref来操纵DOM,可偏偏翻车。

这里分享两个常用的方法,使用以下两个例子为例。

父组件

<template>
	<child ref="childRef"></child>
</template>
<script setup>
import { ref } from "vue";
// 引入子组件
import child from "./child.vue";
// 获取子组件
const childRef = ref(null);
const fun = () => {
	childRef.value.childFun();// 调用子组件的方法
}
</script >

方法一:

defineComponent

如果你使用的是defineComponent定义组件的方法,

那么除了在父组件绑定ref="childRef"外,最关键在于你需要把你想要在父组件中控制的方法return出去。

//子组件一 child
<template>
  <div>
    <a-modal title="Title" v-model:visible="visible" :confirm-loading="confirmLoading" @ok="handleOk">
      <p>{{ modalText }}</p>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { ref, defineComponent } from 'vue';

export default defineComponent({
  setup() {
    const modalText = ref<string>('Content of the modal');
    const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);

    const childFun = () => {
      visible.value = true;
    };

    const handleOk = () => {
      modalText.value = 'The modal will be closed after two seconds';
      confirmLoading.value = true;
      setTimeout(() => {
        visible.value = false;
        confirmLoading.value = false;
      }, 2000);
    };
    return {
      modalText,
      visible,
      confirmLoading,
      childFun,
      handleOk,
    };
  },
});
</script>

在这里插入图片描述

方法二:

setup语法糖

如果你使用的setup导出定义组件的方法,你就需要把将要在父组件中使用的数据和方法使用defineExpose暴露出去。

// 子组件
<script setup>
import { defineExpose } from 'vue'
const childFun = () => {
	console.log('我是子组件方法')
}
// 重点!!这里需要使用defineExpose暴露出去
defineExpose({
	childFun
})
</script>

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值