uni-app学习笔记十五-vue3中defineExpose的使用

发布于:2025-05-27 ⋅ 阅读:(41) ⋅ 点赞:(0)

使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。

可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性。我们可以通过在子组件中defineExpose 暴露一些属性和方法。父组件中可直接调用子组件定义的方法和获取属性值。下面是一个小demo示范下defineExpose的使用。

子组件demo-child.vue

<template>
	<view class="out">
		子组件的值:{{count}}
	</view>
</template>

<script setup>
	import {ref} from "vue"
	const count = ref(100)
	const updateCount = function(){
		count.value++
	}
	defineExpose({
		count,
		name:"XXM",
		updateCount
	})
</script>

子组件中暴露了2个属性count和name,1个方法updateCount。

父组件中使用:

<template>
	<view class="layout">
		<demo-child ref="child"></demo-child>
		<view>--------------</view>
		<button @click="update">点击修改子值</button>
	</view>
</template>

<script setup>
	import {onMounted, ref} from "vue"
	const child = ref(null)
	const update = function(){
		child.value.updateCount()
	}
	onMounted(()=>{
		console.log(child.value)
	})
</script>

上面JS中使用了一个vue3的生命周期钩子函数onMounted,用于在页面未渲染完成时获取值。

上面通过child.value.updateCount()获得子组件定义的方法updateCount。

来看实际效果:

随着按钮的点击,子组件的值由最初的100变成105,调用的是子组件定义的函数updateCount来修改值。当执行点击事件时,页面已渲染完成,因此无需在onMounted取值,在外层即可获取到值。


网站公告

今日签到

点亮在社区的每一天
去签到