vue3中ref獲取子組件的值代碼示例
更新時間:2023年08月16日 10:06:14 作者:我的代碼永沒有bug
這篇文章主要給大家介紹了關(guān)于vue3中ref獲取子組件值的相關(guān)資料,在Vue3中父組件獲取子組件的值可以通過使用'ref'和'$refs'來實現(xiàn),文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下
一、< script setup >通過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暴露的值或方法才能被父組件通過ref訪問
defineExpose({
accountLoginAction
});二、setup()通過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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
FastApi+Vue+LayUI實現(xiàn)前后端分離的示例代碼
本文主要介紹了FastApi+Vue+LayUI實現(xiàn)前后端分離的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
vue3為什么要用proxy替代defineProperty
這篇文章主要介紹了vue3為什么要用proxy替代defineProperty,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
Vue3如何理解ref toRef和toRefs的區(qū)別
本文主要介紹了Vue3如何理解ref toRef和toRefs的區(qū)別,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
Vue3項目中配置TypeScript和JavaScript的兼容
在Vue3開發(fā)中,常見的使用JavaScript(JS)編寫代碼,但也會有調(diào)整編寫語言使用TypeScript(TS)的需求,因此,在Vue3項目設(shè)置中兼容TS和JS是刻不容緩的重要任務(wù),2023-08-08

