一、< 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>
文章來源地址http://www.zghlxwxcb.cn/news/detail-560836.html
文章來源:http://www.zghlxwxcb.cn/news/detail-560836.html
到了這里,關于vue3中ref獲取子組件的值的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!