Vue3 setup语法糖访问组件实例

66 阅读1分钟

Vue3 setup语法糖访问组件实例

子组件使用defineExpose声明需要暴露出去的变量 父组件通过同名Ref对象接收子组件的实例,使用实例调用被暴露出来的变量 子组件

<template>
    <div>
        <div>this is a LocalComponent</div>
    </div>
</template>
<script lang="ts" setup>
import { defineExpose, ref} from 'vue';

const age = ref(12);
const add = () => {
    console.log(age.value + 1);
}

// 声明需要导出的变量
defineExpose({
    age,add
})
</script>

父组件

<template>
  <div>
    <LocalComponent ref="localVal">

    </LocalComponent>

  </div>
</template>
<script setup lang="ts">
import { ref,onMounted } from "vue";
import LocalComponent from "../components/component/LocalComponent.vue";

const localVal = ref(null);

onMounted(() => {
  localVal.value.add();
  console.log(localVal.value);
  console.log(localVal.value.age);

})
</script>