一、setup()函数通过ref获取子组件的值或方法

父组件

<template>
    <div>
      <Child ref="childRef" />
    </div>
</template>
<script lang="ts">
import { onMounted, ref, reactive, nextTick, toRefs, computed, provide } from 'vue';
import Child from './components/Child.vue'; //引入子组件
export default {
  components: {
    Child,
  },
  setup() {
    const childRef = ref();//定义子组件的ref
    
    //打印子组件的ref的值
    function getChildRefValue(value) {
      console.log(childRef.value);
    }
    onMounted(() => {
      console.log('子组件ref对象',childRef.value);
      console.log('获取子组件的childValue值',childRef.value.childValue);
      console.log('调用子组件的childFunction方法',childRef.value.childFunction);
    });

    return {
      getChildRefValue,
      childRef,//记得要返回子组件的ref,不然访问不到
    };
  },
};
</script>

子组件

<script lang="ts">
import { onMounted, ref, reactive, nextTick, toRefs, computed, provide } from 'vue';
export default {
  setup() {
    const childValue=ref('我是子组件的的值')
    
    //打印子组件的ref的值
    function childFunction() {
     console.log('我是子组件的方法');
    }

    return {
      childValue,
      childFunction,
    };
  },
};
</script>

二、<script setup>通过ref获取子组件的值或方法

父组件

<template>
    <div>
      <Child ref="childRef" />
    </div>
</template>

	<script setup lang="ts">
import { onMounted, ref, reactive, nextTick, toRefs, computed, provide } from 'vue';
import Child from './components/Child.vue'; //引入子组件

const childRef = ref(); //定义子组件的ref

onMounted(() => {
      console.log('子组件ref对象',childRef.value);
      console.log('获取子组件的childValue值',childRef.value.childValue);
      console.log('调用子组件的childFunction方法',childRef.value.childFunction);
});
</script>

子组件

<script setup lang="ts">
import { ref, computed, watch, watchEffect, defineEmits, defineProps, withDefaults, inject } from 'vue';
/* 定义被父组件可以访问的值或方法 start */
const childValue = ref('我是子组件的值');
function childFunction() {
  console.log('我是子组件的方法');
}
/* 定义被父组件可以访问的值或方法 end */

/* 只有defineExpose暴露的值或方法才能被父组件通过ref访问 start */
defineExpose({
  childValue,
  childFunction,
});
/* 只有defineExpose暴露的值或方法才能被父组件通过ref访问 end */
</script>
Logo

前往低代码交流专区

更多推荐