vue3 setup语法糖下父组件如何调用子组件
作者:左直拳
这篇文章主要介绍了vue3 setup语法糖下父组件如何调用子组件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue3 setup语法糖下父组件调用子组件
vue3下,父组件调用子组件的方法,如果使用了<script setup>
这种写法,那么子组件方法需要采用defineExpose()
进行修饰,才能被外界调用。
上代码:
1、子组件
_pop.vue:
<template> 。。。 </template> <script setup> import { defineExpose } from "vue"; const popIt = () => { 。。。 }; defineExpose({ popIt }); </script>
2、父组件
<template> <pop pTitle="hehe" ref="pop1"></pop> </template> <script setup> import pop from "./_pop"; const pop1 = ref(); pop1.value.popIt(); </script>
vue3 父子组件相互调用
下面演示均为使用 setup 语法糖的情况!
参考网址:https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
父组件调用子组件方法
子组件需要使用defineExpose对外暴露方法,父组件才可以调用!
1.子组件
<template> <div>我是子组件</div> </template> <script lang="ts" setup> // 第一步:定义子组件的方法 const hello = (str: string) => { console.log('子组件的hello方法执行了--' + str) } // 第二部:暴露方法 defineExpose({ hello }) </script>
2.父组件
<template> <button @click="getChild">触发子组件方法</button> <!-- 一:定义 ref --> <Child ref="childRef"></Child> </template> <script lang="ts" setup> import { ref } from 'vue'; import Child from '../../components/child.vue'; // 二:定义与 ref 同名变量 const childRef = ref <any> () // 三、函数 const getChild = () => { // 调用子组件的方法或者变量,通过value childRef.value.hello("hello world!"); } </script>
3.测试结果
子组件调用父组件方法
1.父组件
<template> <Child @sayHello="handle"></Child> </template> <script lang="ts" setup> import Child from '../../components/child.vue'; const handle = () => { console.log('子组件调用了父组件的方法') } </script>
2.子组件
<template> <view>我是子组件</view> <button @click="say">调用父组件的方法</button> </template> <script lang="ts" setup> const emit = defineEmits(["sayHello"]) const say = () => { emit('sayHello') } </script>
3.测试结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。