1. <script setup> Get the value or method of a child component through ref
Parent component:
<pane-account ref="accountRef"></pane-account> <script lang="ts" setup> import { ref } from 'vue'; import PaneAccount from './'; const accountRef = ref<InstanceType<typeof PaneAccount>>(); const loginAction = () => { // Parent component gets the ref value of the child component ?.accountLoginAction(); }; </script>
Subcomponents:
<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 = () => { ?.validate((valid) => { if (valid) { ('Log in'); } else { ('222'); } }); }; // Only the value or method exposed by defineExpose can be accessed by the parent component through refdefineExpose({ accountLoginAction });
2. setup() gets the value of the child component through ref
Parent component:
<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 = () => { ?.accountLoginAction() } return { loginAction, accountRef } } }) </script>
Subcomponents:
<script lang="ts"> import { defineComponent, PropType, computed, ref } from 'vue' export default defineComponent({ setup(props, { emit }) { const accountLoginAction = () => { ('Methods of Subcomponents') } return { accountLoginAction } } }) </script>
Summarize
This is the end of this article about ref obtaining the value of child components in vue3. For more related content about ref obtaining the value of child components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!