vue3通过ref获取子组件defineExpose的数据和方法
更新时间:2023年10月09日 09:29:34 作者:qq_42750608
defineExpose是Vue3中新增的选项,用于向父组件暴露子组件内部的属性和方法,通过defineExpose,子组件可以主动控制哪些属性和方法可以被父组件访问,本文主要介绍了vue3通过ref获取子组件defineExpose的数据和方法,需要的朋友可以参考下
1. 父组件:
<script setup>
import { defineAsyncComponent, watchEffect, toRefs, reactive } from 'vue';
// 异步组件
const Test = defineAsyncComponent(()=>import('./xx/Test.vue'))
const child1Ref = ref(null)
const state = reactive({
age: 1,
name: '2',
sayHello: null,
})
watchEffect(() => {
// 拿到子组件的一些数据
console.log(child1Ref.value)
const obj = toRefs(child1Ref.value)
console.log(obj.a, obj.b)
state.name = obj.b
state.age = obj.a
state.sayHello = obj.onSayHello
})
</script>
<template>
{{ state.age }} -- {{ state.name }}
<button @click="state.sayHello">say hello</button>
<Test ref="child1Ref"/>
</template>2. 子组件
<script setup>
import { ref, defineExpose } from 'vue'
const a = ref(101)
const b = ref('sddewfewfew')
const onSayHello = () => {
console.log('hello')
}
defineExpose({
a,
b,
onSayHello,
})
</script>
<template>
<p>Child1</p>
</template>到此这篇关于vue3通过ref获取子组件defineExpose的数据和方法的文章就介绍到这了,更多相关vue3获取defineExpose内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Element中table组件(el-table)右侧滚动条空白占位处理
当我设置了max-height,就会在表格右侧出现一列空白的占位,本文主要介绍了Element中table组件(el-table)右侧滚动条空白占位处理,感兴趣的可以了解一下2023-09-09
vue+element-ui+sortable.js实现表格拖拽功能
这篇文章主要为大家详细介绍了vue+element-ui+sortable.js实现表格拖拽功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-04-04


最新评论