Vue3中父子组件相互触发方法

1. 父组件触发子组件的方法

 父组件代码如下:

<template>
    <div class="parent">
        <button @click="getChild">触发子组件方法</button>
        <!-- 1. 定义ref -->
        <child ref="childRef"></child>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import child from "@/components/child.vue";

export default defineComponent({
    setup() {
        // 2. 定义与ref同名变量
        const childRef = ref<any>();
        const getChild = () => {
            // 3. 调用子组件的方法或者变量,通过value
            childRef.value.doSomething();
        }
        return {
            // 4. return 该变量
            childRef,
            getChild
        };
    },
    components: {
        child,

    },
});
</script>

 子组件代码如下:

<template>
    <div class="child">
    </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";


export default defineComponent({
    setup() {
        // 1. 定义子组件的方法
        const doSomething = () => {
            console.log('已触发组件方法');
        }
        return {
            // 2. return 该方法
            doSomething
        };
    },
   
});
</script>

效果:

2.子组件触发父组件的方法

 父组件代码如下:

<template>
    <div class="parent">
        <!-- 1. 接受方法名 -->
        <child @postData="postData"></child>
    </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import child from "@/components/child.vue";

export default defineComponent({
    setup() {
        // 2. 定义方法
        const postData = () => {
            console.log('触发父组件的方法');
        }
        return {
            // 3. return 出来
            postData
        };
    },
    components: {
        child,
    },
});
</script>

 子组件代码如下:

<template>
    <div class="child">
    </div>
</template>
<script lang="ts">
import { defineComponent, onMounted } from "vue";


export default defineComponent({
    setup(props, context) {
        const doSomething = () => {
            // 与vue2不同的是要通过 context 来找到 emit
            context.emit('postData');
        }
        onMounted(() => {
            doSomething();
        })
        return {
        };
    },
   
});
</script>

效果如下:

 

 Ps:1. 该测试环境为 vue3 + Ts 

         2. 如果需要传值和 vue2 类似

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值