vue3中使用getCurrentInstance通过ref调用子组件属性与方法

话不多说: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>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3使用ref调用组件方法有一些变化。首先,在父组件的setup函数导入ref方法。然后,使用ref创建一个变量来引用组件。这个变量可以通过ref的.value属性来访问组件方法。例如,在父组件,你可以这样使用ref调用组件方法: ```javascript import { ref } from 'vue' setup() { const eleTable = ref() const clickSon = () => { eleTable.value.changeShowText() // 调用组件方法 let arr = eleTable.value.tableData // 获取组件setup里面定义的变量 } return { eleTable, clickSon } } ``` 这样,你就可以通过eleTable.value来调用组件的changeShowText方法了。注意,eleTable.value是一个对象,所以你可以像上面的例那样操作它的属性方法。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [vue3.0使用ref调用组件方法](https://blog.csdn.net/qq_41619796/article/details/114291319)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [浏览器显示数据库数据的条形图柱状图 前后端分离vue.js+spring boot 计算机软件工程课程设计毕业设计 ...](https://download.csdn.net/download/Amzmks/88275824)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值