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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
vue结合el-dialog封装自己的confirm二次确认弹窗方式
这篇文章主要介绍了vue结合el-dialog封装自己的confirm二次确认弹窗方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-08-08
vue-cli2,vue-cli3,vite 生产环境去掉console.log
console.log一般都是在开发环境下使用的,在生产环境下需要去除 ,本文主要介绍了vue-cli2,vue-cli3,vite 生产环境去掉console.log,具有一定的参考价值,感兴趣的可以了解一下2024-05-05


最新评论