vue3組合式API獲取子組件屬性和方法的代碼實例
更新時間:2024年01月30日 11:41:32 作者:椒鹽大肥貓
這篇文章主要為大家詳細介紹了vue3組合式API獲取子組件屬性和方法的代碼實例,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
在vue2中,獲取子組件實例的方法或者屬性時,父組件直接通過ref即可直接獲取子組件的屬性和方法,如下:
// father.vue
<child ref="instanceRef" />
this.$ref['instanceRef'].testVal
this.$ref['instanceRef'].testFunc()
// child.vue
data () {
return {
testVal: '來自子組件的屬性'
}
},
methods: {
testFunc() {
return '來自子組件的方法'
}
}
在vue3 組合式API中,在子組件使用defineExpose指定需要暴露的屬性和方法,父組件才可以通過ref獲取到子組件的屬性和方法,如下:
// father.vue
<script setup lang="ts">
import ChildInstance from "@/views/component/father-instance/child-instance.vue";
import { ref } from "vue";
const instanceRef = ref(null);
const getChildInstance = () => {
const childInstance = instanceRef.value; // 通過ref獲取子組件實例
console.log(childInstance.childValue);
console.log(childInstance.childFunc());
};
</script>
<template>
<ChildInstance ref="instanceRef" />
<el-button @click="getChildInstance">獲取子組件屬性和方法</el-button>
</template>
<style scoped lang="scss"></style>
// child.vue
<script setup lang="ts">
import { ref, defineExpose } from "vue";
const childValue = ref("來自子組件的屬性");
const childFunc = () => {
return "來自子組件的方法";
};
// 使用defineExpose指定需要暴露的屬性和方法
defineExpose({
childValue,
childFunc
});
</script>
<template>
<div>來自子組件</div>
</template>
<style scoped lang="scss"></style>
以上就是vue3組合式API獲取子組件屬性和方法的代碼實例的詳細內(nèi)容,更多關(guān)于vue3 API獲取子組件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue2實現(xiàn)provide inject傳遞響應式
在看element-ui的源碼的時候,注意到源碼里面有很多地方使用provide和inject的屬性,本文主要介紹了vue2實現(xiàn)provide inject傳遞響應式,分享給大家,感興趣的可以了解一下2021-05-05
Vue+Echarts實現(xiàn)繪制動態(tài)折線圖
這篇文章主要為大家詳細介紹了如何利用Vue和Echarts實現(xiàn)繪制動態(tài)折線圖,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-03-03
VueJS 組件參數(shù)名命名與組件屬性轉(zhuǎn)化問題
這篇文章主要介紹了VueJS 組件參數(shù)名命名與組件屬性轉(zhuǎn)化問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-12-12
vue中使用百度腦圖kityminder-core二次開發(fā)的實現(xiàn)
這篇文章主要介紹了vue中使用百度腦圖kityminder-core二次開發(fā)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09

