vue3中ref获取子组件的值

一、< 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>

猜你喜欢

转载自blog.csdn.net/weixin_48300785/article/details/128819238