vue3父組件調(diào)用子組件的方法例子
前言
vue3父組件調(diào)用子組件的方法是通過expose
和ref
來實(shí)現(xiàn)的,我們可以通過expose
來控制父組件可以訪問子組件那些的方法和對象,我們將通過setup api
(組合式 api)和option api
(選項(xiàng)式 api)來演示父組件如何調(diào)用子組件的方法。
1,組合式API
父組件通過ref定義子組件實(shí)例,通過調(diào)用實(shí)例獲得子組件的數(shù)據(jù)和方法
<!-- 父組件 app.vue --> <template> <div class="itxst"> <!-- 使用 ref 指令關(guān)聯(lián)子組件 --> <child ref="childComp"/> <button @click="onTry">點(diǎn)擊試一試</button> </div> </template> <script setup> import { reactive, ref } from "vue"; import child from "./child.vue"; //定義子組件實(shí)例,名稱要和上面的ref相同 const childComp = ref(null); //訪問demo組件的方法或?qū)ο? const onTry = () => { //獲取到子組件的 title 數(shù)據(jù) let msg = childComp.value.state.title; //調(diào)用子組件的 play方法 childComp.value.play(); }; </script>
子組件通過defineExpose暴露對象和方法
<!--子組件名稱 child.vue --> <template> <div class="itxst"> {{ state.title }} </div> </template> <script setup> import { ref, reactive } from "vue"; //定義一個(gè)變量 const state = reactive({ title: "www.itxst.com", }); //定義一個(gè)方法 const play = () => { state.title = "你調(diào)用了子組件的方法"; }; //暴露state和play方法 defineExpose({ state, play, }); </script>
2,選項(xiàng)式API
<!-- 父組件 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.message; //執(zhí)行了子組件的 play方法 this.$refs.childComp.play(); }, }, }; </script>
<!-- 子組件 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>
總結(jié)
到此這篇關(guān)于vue3父組件調(diào)用子組件的文章就介紹到這了,更多相關(guān)vue3父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue實(shí)現(xiàn)登錄、注冊、退出、跳轉(zhuǎn)等功能
這篇文章主要介紹了vue實(shí)現(xiàn)登錄、注冊、退出、跳轉(zhuǎn)等功能,需要的朋友可以參考下2020-12-12vue-cli下的vuex的簡單Demo圖解(實(shí)現(xiàn)加1減1操作)
這篇文章主要介紹了vue-cli下的vuex的簡單Demo(實(shí)現(xiàn)加1減1操作),本文圖文并茂給大家介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-02-02Vue 實(shí)現(xiàn)對quill-editor組件中的工具欄添加title
這篇文章主要介紹了Vue 實(shí)現(xiàn)對quill-editor組件中的工具欄添加title,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08vue中this.$http.post()跨域和請求參數(shù)丟失的解決
這篇文章主要介紹了vue中this.$http.post()跨域和請求參數(shù)丟失的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04