vue3父子組件相互調(diào)用方法詳解
1、前言
在vue3項(xiàng)目開發(fā)中,我們常常會遇到父子組件相互調(diào)用的場景,下面主要以setup語法糖格式詳細(xì)聊聊父子組件那些事兒
2、子組件調(diào)用父組件方法(setup組合式)
2.1 父組件Father.vue
<template> <child @sayHello="handle" /> </template> <script setup> import Child from './components/child.vue'; const handle = () => { console.log('子組件調(diào)用了父組件的方法') } </script>
2.2 子組件Child.vue
<template> <view>我是子組件</view> <button @click="sayHello">調(diào)用父組件的方法</button> </template> <script setup> const emit = defineEmits(["sayHello"]) const sayHello = () => { emit('Hello World') } </script>
3、父組件調(diào)用子組件方法(setup組合式)
3.1 子組件Child.vue
<template> <div>我是子組件</div> </template> <script setup> // 第一步:定義子組件的方法 const sayHello = (value) => { console.log(value) } // 第二部:暴露方法 defineExpose({ sayHello }) </script>
3.2 父組件Father.vue
<template> <button @click="getChild">觸發(fā)子組件方法</button> <child ref="childRef" /> </template> <script setup> import Child from './components/child.vue' // 定義與 ref 同名變量 const childRef = ref(null) const getChild = () => { // 調(diào)用子組件的方法或者變量,通過value childRef.value.hello("hello world!"); } </script>
4、簡單說下選項(xiàng)式API的寫法
不推薦,vue3能寫組合式就寫組合式
4.1 父組件 app.vue
<template> <div class="itxst"> <!-- 使用 ref 命令 --> <child ref="childComp"/> <button @click="onClick">點(diǎn)擊試一試</button> </div> </template> <script > import child from "./child.vue"; export default { name: "app", //注冊組件 components: { child, }, methods: { onClick: function () { //獲取到 子組件的 數(shù)據(jù) let msg = this.$refs.childComp.title; //執(zhí)行了子組件的 play方法 this.$refs.childComp.play(); }, }, }; </script>
4.2 子組件 child.vue
<template> <div class="itxst"> {{ title }} </div> </template> <script> //選項(xiàng)式默認(rèn)當(dāng)前實(shí)例是全部暴露 export default { name: "demo", //默認(rèn)全部暴露 也可以通過expose控制那些需要暴露 //expose: ['play'], data() { return { title: "www.itxst.com", }; }, methods: { play: function () { this.title = "你調(diào)用了子組件的方法"; }, }, }; </script>
到此這篇關(guān)于vue3父子組件相互調(diào)用方法詳解的文章就介紹到這了,更多相關(guān)vue3父子組件相互調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3.0中給自己添加一個(gè)vue.config.js配置文件
這篇文章主要介紹了vue3.0中給自己添加一個(gè)vue.config.js配置文件方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07Vue數(shù)據(jù)驅(qū)動(dòng)模擬實(shí)現(xiàn)1
這篇文章主要介紹了Vue數(shù)據(jù)驅(qū)動(dòng)模擬實(shí)現(xiàn)的相關(guān)資料,允許采用簡潔的模板語法聲明式的將數(shù)據(jù)渲染進(jìn)DOM,且數(shù)據(jù)與DOM綁定在一起,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例
這篇文章主要介紹了基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02詳解vue beforeEach 死循環(huán)問題解決方法
這篇文章主要介紹了vue beforeEach 死循環(huán)問題解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02vue實(shí)現(xiàn)樣式之間的切換及vue動(dòng)態(tài)樣式的實(shí)現(xiàn)方法
這篇文章主要介紹了vue中如何實(shí)現(xiàn)樣式之間的切換及vue動(dòng)態(tài)樣式的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-12-12