Vue3父子組件相互調(diào)用方法舉例詳解
更新時間:2023年08月15日 11:16:40 作者:不甜吶
這篇文章主要給大家介紹了關(guān)于Vue3父子組件相互調(diào)用方法的相關(guān)資料,vue中我們常常用到組件,那么組件中互相調(diào)用也是經(jīng)常遇到的,需要的朋友可以參考下
下面演示均為使用 setup 語法糖的情況!
參考網(wǎng)址:https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
一、父組件調(diào)用子組件方法
子組件需要使用defineExpose對外暴露方法,父組件才可以調(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)用子組件的方法或者變量,通過value
childRef.value.hello("hello world!");
}
</script>3.測試結(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.測試結(jié)果

總結(jié)
到此這篇關(guān)于Vue3父子組件相互調(diào)用方法的文章就介紹到這了,更多相關(guān)Vue3父子組件相互調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue實現(xiàn)el-table點選和鼠標框選功能的方法
在Vue中我們經(jīng)常需要處理表格數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于vue實現(xiàn)el-table點選和鼠標框選功能的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-10-10
uniApp?h5項目如何通過命令行打包并生成指定路徑及文件名稱
用uni-app來寫安卓端,近日需要將程序打包為H5放到web服務器上,經(jīng)過一番折騰,這里給大家分享下,這篇文章主要給大家介紹了關(guān)于uniApp?h5項目如何通過命令行打包并生成指定路徑及文件名稱的相關(guān)資料,需要的朋友可以參考下2024-02-02
vue 點擊按鈕實現(xiàn)動態(tài)掛載子組件的方法
今天小編就為大家分享一篇vue 點擊按鈕實現(xiàn)動態(tài)掛載子組件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

