vue3中ref獲取子組件的值代碼示例
更新時(shí)間:2023年08月16日 10:06:14 作者:我的代碼永沒(méi)有bug
這篇文章主要給大家介紹了關(guān)于vue3中ref獲取子組件值的相關(guān)資料,在Vue3中父組件獲取子組件的值可以通過(guò)使用'ref'和'$refs'來(lái)實(shí)現(xiàn),文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
一、< script setup >通過(guò)ref獲取子組件的值或方法
父組件:
<pane-account ref="accountRef"></pane-account>
<script lang="ts" setup>
import { ref } from 'vue';
import PaneAccount from './pane-account.vue';
const accountRef = ref<InstanceType<typeof PaneAccount>>();
const loginAction = () => {
// 父組件獲取子組件ref值
accountRef.value?.accountLoginAction();
};
</script>子組件:
<script lang="ts" setup>
import { ref, reactive, defineProps, defineExpose } from 'vue';
import type { ElForm } from 'element-plus';
const formRef = ref<InstanceType<typeof ElForm>>();
const accountLoginAction = () => {
formRef.value?.validate((valid) => {
if (valid) {
console.log('登錄');
} else {
console.log('222');
}
});
};
// 只有defineExpose暴露的值或方法才能被父組件通過(guò)ref訪問(wèn)
defineExpose({
accountLoginAction
});二、setup()通過(guò)ref獲取子組件值
父組件:
<pane-account ref="accountRef"></pane-account>
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
export default defineComponent({
setup() {
const accountRef = ref<InstanceType<typeof LoginAccount>>()
const loginAction = () => {
accountRef.value?.accountLoginAction()
}
return {
loginAction,
accountRef
}
}
})
</script>子組件:
<script lang="ts">
import { defineComponent, PropType, computed, ref } from 'vue'
export default defineComponent({
setup(props, { emit }) {
const accountLoginAction = () => {
console.log('子組件的方法')
}
return {
accountLoginAction
}
}
})
</script>總結(jié)
到此這篇關(guān)于vue3中ref獲取子組件的值的文章就介紹到這了,更多相關(guān)vue3 ref獲取子組件值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue+ElementUI實(shí)現(xiàn)從后臺(tái)動(dòng)態(tài)填充下拉框的示例代碼
本文主要介紹了Vue+ElementUI實(shí)現(xiàn)從后臺(tái)動(dòng)態(tài)填充下拉框的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Vue2利用Axios發(fā)起請(qǐng)求的詳細(xì)過(guò)程記錄
有很多時(shí)候你在構(gòu)建應(yīng)用時(shí)需要訪問(wèn)一個(gè)API并展示其數(shù)據(jù),做這件事的方法有好幾種,而使用基于promise的HTTP客戶端axios則是其中非常流行的一種,這篇文章主要給大家介紹了關(guān)于Vue2利用Axios發(fā)起請(qǐng)求的詳細(xì)過(guò)程,需要的朋友可以參考下2021-12-12
Vue項(xiàng)目打包部署到GitHub Pages的實(shí)現(xiàn)步驟
本文主要介紹了Vue項(xiàng)目打包部署到GitHub Pages的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
vue實(shí)現(xiàn)拖拽滑動(dòng)分割面板
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)拖拽滑動(dòng)分割面板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

