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

父组件

<template>
    <div class="parent">
        <button @click="getChild">触发子组件方法</button>
        <!-- 1. 定义ref -->
        <child ref="childRef"></child>
    </div>
</template>
<script lang="ts" stup>
    import { defineComponent, ref } from "vue";
    import child from "@/components/child.vue";
 
    // 2. 定义与ref同名变量
    const childRef = ref<any>();
    const getChild = () => {
        childRef.value.childFun();
    }
</script>

子组件 scrip setup 写法

<template>
    <div class="child">
    </div>
</template>
<script lang="ts" stup>

 const childFun = () => {
     console.log('已触发组件方法');
 }

 //关键点 把 方法暴露给父组件
 defineExpose({open})

</script>

子组件 defineComponent 写法

<template>
    <div class="child">
    </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
 
 
export default defineComponent({
    setup() {
        // 子组件的方法
        const childFun = () => {
            console.log('已触发组件方法');
        }
        return {
            childFun
        };
    },
   
});
</script>

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue 3中,可以使用`ref`和`toRefs`函数来实现在组件调用组件方法。 首先,在组件的`setup`函数中,将需要在组件调用方法定义为一个`ref`。然后,通过`toRefs`函数将`ref`转换为具有响应式特性的对象。 以下是一个示例: ```vue <template> <div> <p>组件</p> <button @click="increment">增加</button> </div> </template> <script> import { ref, toRefs } from 'vue'; export default { setup() { const count = ref(0); const increment = () => { count.value++; }; return { ...toRefs(count), increment }; } }; </script> ``` 在上面的示例中,组件中定义了一个`count`变量并初始化为0,以及一个`increment`方法用于增加`count`的值。通过`toRefs(count)`将`count`转换为具有响应式特性的对象。 然后,在组件中可以使用`ref`和`toRefs`函数来获取组件方法,并进行调用。 ```vue <template> <div> <p>组件</p> <p>组件的 count 值:{{ childCount }}</p> <button @click="childIncrement">调用组件方法</button> </div> </template> <script> import { ref, toRefs } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const childComponentRef = ref(null); const childCount = ref(0); const childIncrement = () => { childComponentRef.value.increment(); childCount.value = childComponentRef.value.count.value; }; return { ...toRefs(childCount), childIncrement, childComponentRef }; } }; </script> ``` 在上面的示例中,组件中定义了一个`childComponentRef`变量用于获取组件实例,以及一个`childCount`变量用于显示组件的`count`值。 通过`childComponentRef.value.increment()`调用组件的`increment`方法,并通过`childCount.value = childComponentRef.value.count.value`更新组件中显示的组件的`count`值。 这样就实现了在组件调用组件方法。注意,使用`ref`和`toRefs`函数可以确保获取到的是响应式的数据。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值