一、< 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 = () => {
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({
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>