vue3 父组件调用子组件方法

一.setup语法糖写法

1.子组件通过defineExpose暴露对象和方法 

child.vue

<template>
	。。。
</template>

<script setup>
	import { defineExpose } from "vue";
	
	const click = () => {
		。。。
	};
	defineExpose({ click });
</script>

2.父组件

<template>
	<child ref="refChild" ref="child"></pop>
</template>

<script setup>
	import child from "./child";

	const refChild = ref();
	refChild.value.click();
</script>

二.选项式API写法

        父组件:

<!-- 父组件 app.vue -->
<template>
  <div class="itxst">
    <!-- 使用 ref  命令 -->
    <child ref="childComp"/>
    <button @click="onClick">点击试一试</button>
  </div>
</template>
<script >
import child from "./child.vue";
export default {
  name: "app",
  //注册组件
  components: {
    child,
  },
  methods: {
    onClick: function () {
      //获取到 子组件的  数据
      let msg = this.$refs.childComp.message;
      //执行了子组件的 play方法
      this.$refs.childComp.play();
    },
  },
};
</script> 

        子组件: 

<!-- 子组件 child.vue -->
<template>
  <div class="itxst">
    {{ title }}
  </div>
</template>
<script>
//选项式默认当前实例是全部暴露
export default {
  name: "demo",
  //默认全部暴露 也可以通过expose控制那些需要暴露
  //expose: ['play'],
  data() {
    return {
      title: "www.itxst.com",
    };
  },
  methods: {
    play: function () {
      this.title = "你调用了子组件的方法";
    },
  },
};
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值