vue3のrefでサブコンポーネントの値を取得する

1. <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
});

2. 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