vue3中使用getCurrentInstance通过ref调用子组件属性与方法
1.setup语法糖中导入子组件2.在子组件标签上绑定ref值3.setup内部从vue中按需导出 getCurrentInstance 方法4.调用getCurrentInstance方法导出proxy5.通过proxy.$refs.子组件ref名.子组件内属性/方法 实现调用子组件中:js内需要通过defineExpose导出父组件需要使用的属性和方法即可
·
话不多说:vue3父组件调用子组件内部属性和方法示例
父组件中:
1.setup语法糖中导入子组件
2.在子组件标签上绑定ref值
3.setup内部从vue中按需导出 getCurrentInstance 方法
4.调用getCurrentInstance方法导出proxy
5.通过proxy.$refs.子组件ref名.子组件内属性/方法 实现调用
<template>
<!-- 父组件 -->
<div>
<!-- 子组件 -->
<Child ref="child" />
<button @click="changeChildren">子组件count+1</button>
</div>
</template>
<script setup lang="ts" name="Father">
import { getCurrentInstance, ComponetInternalInstance,ref } from "vue";
import Child from "./zi.vue";
const child = ref(null)
// as ComponetInternalInstance表示类型断言,ts时使用。否则报错,proxy为null
const { proxy } = getCurrentInstance() as ComponetInternalInstance;
function changeChildren() {
proxy.$refs.child.count += 1;
//也可以使用ref数据.value的形式调用:
//child.value.count += 1
console.log(child.value.name)
}
</script>
<style scoped></style>
子组件中:
1.js内需要通过defineExpose导出父组件需要使用的属性和方法即可
因为使用 <script setup>
的组件是默认关闭的——即通过模板引用或者 $parent
链获取到的组件的公开实例,不会暴露任何在 <script setup>
中声明的绑定。
可以通过 defineExpose编译器宏来显式指定在 <script setup>
组件中要暴露出去的属性:
关于defineExpose: 单文件组件
<template>
<div>
<!-- 子组件 -->
<div>子组件count:{{ count }}</div>
</div>
</template>
<script setup lang="ts" name="Child">
import { ref, defineExpose } from "vue";
const count = ref(0);
defineExpose({
count,
});
</script>
<style scoped></style>
更多推荐
已为社区贡献15条内容
所有评论(0)