Vue3父子組件相互調用方法舉例詳解
更新時間:2023年08月15日 11:16:40 作者:不甜吶
這篇文章主要給大家介紹了關于Vue3父子組件相互調用方法的相關資料,vue中我們常常用到組件,那么組件中互相調用也是經常遇到的,需要的朋友可以參考下
下面演示均為使用 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方法執(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> () // 三、函數 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.測試結果
總結
到此這篇關于Vue3父子組件相互調用方法的文章就介紹到這了,更多相關Vue3父子組件相互調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
uniApp?h5項目如何通過命令行打包并生成指定路徑及文件名稱
用uni-app來寫安卓端,近日需要將程序打包為H5放到web服務器上,經過一番折騰,這里給大家分享下,這篇文章主要給大家介紹了關于uniApp?h5項目如何通過命令行打包并生成指定路徑及文件名稱的相關資料,需要的朋友可以參考下2024-02-02