vue3?setup語(yǔ)法糖下父組件如何調(diào)用子組件
vue3 setup語(yǔ)法糖下父組件調(diào)用子組件
vue3下,父組件調(diào)用子組件的方法,如果使用了<script setup> 這種寫(xiě)法,那么子組件方法需要采用defineExpose()進(jìn)行修飾,才能被外界調(diào)用。
上代碼:
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 父子組件相互調(diào)用
下面演示均為使用 setup 語(yǔ)法糖的情況!
參考網(wǎng)址:https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
父組件調(diào)用子組件方法
子組件需要使用defineExpose對(duì)外暴露方法,父組件才可以調(diào)用!
1.子組件
<template>
<div>我是子組件</div>
</template>
<script lang="ts" setup>
// 第一步:定義子組件的方法
const hello = (str: string) => {
console.log('子組件的hello方法執(zhí)行了--' + str)
}
// 第二部:暴露方法
defineExpose({
hello
})
</script>2.父組件
<template>
<button @click="getChild">觸發(fā)子組件方法</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> ()
// 三、函數(shù)
const getChild = () => {
// 調(diào)用子組件的方法或者變量,通過(guò)value
childRef.value.hello("hello world!");
}
</script>3.測(cè)試結(jié)果

子組件調(diào)用父組件方法
1.父組件
<template>
<Child @sayHello="handle"></Child>
</template>
<script lang="ts" setup>
import Child from '../../components/child.vue';
const handle = () => {
console.log('子組件調(diào)用了父組件的方法')
}
</script>2.子組件
<template>
<view>我是子組件</view>
<button @click="say">調(diào)用父組件的方法</button>
</template>
<script lang="ts" setup>
const emit = defineEmits(["sayHello"])
const say = () => {
emit('sayHello')
}
</script>3.測(cè)試結(jié)果

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue中v-model和v-bind綁定數(shù)據(jù)的異同
這篇文章主要介紹了vue中v-model和v-bind綁定數(shù)據(jù)的異同,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
vue 自定義提示框(Toast)組件的實(shí)現(xiàn)代碼
這篇文章主要介紹了vue 自定義提示框(Toast)組件的實(shí)現(xiàn)代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
vue如何對(duì)一個(gè)數(shù)據(jù)過(guò)濾出想要的item
這篇文章主要介紹了vue如何對(duì)一個(gè)數(shù)據(jù)過(guò)濾出想要的item問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue Tooltip提示動(dòng)態(tài)換行問(wèn)題
這篇文章主要介紹了vue Tooltip提示動(dòng)態(tài)換行問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
vue.js中關(guān)于點(diǎn)擊事件方法的使用(click)
這篇文章主要介紹了vue.js中關(guān)于點(diǎn)擊事件方法的使用(click),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
element-ui中select組件綁定值改變,觸發(fā)change事件方法
今天小編就為大家分享一篇element-ui中select組件綁定值改變,觸發(fā)change事件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
vue3實(shí)現(xiàn)動(dòng)態(tài)添加路由
這篇文章主要介紹了vue3實(shí)現(xiàn)動(dòng)態(tài)添加路由方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04

