vue3 setup lang=“ts“ defineExpose

vue3 setup lang=“ts” defineExpose

 /**
 * Vue `<script setup>` compiler macro for declaring a component's exposed
 * instance properties when it is accessed by a parent component via template
 * refs.
 *
 * `<script setup>` components are closed by default - i.e. variables inside
 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
 * via `defineExpose`.
 *
 * This is only usable inside `<script setup>`, is compiled away in the
 * output and should **not** be actually called at runtime.
 */

机翻
Vue <script setup>编译器宏,当父组件通过模板引用访问它时,用来声明组件的公开实例属性。
<script setup>组件在默认情况下是关闭的——也就是说,<script setup>范围内的变量不会向父变量公开,除非通过defineExpose显式地公开。
这只在<script setup>中可用,在输出中编译,不应该在运行时实际调用。

● 暴露reactive对象的时候可以将响应式对象转换为普通对象
● 不然父组件只能拿到初始值
子组件

	<script setup lang="ts">
	const Son = reactive({
	  msg: 'Son',
	  coast: 120,
	});
	setInterval(() => {
	  if (Son.coast < 125) {
	    Son.coast++;
	  }
	}, 1000);
	/* type_one 这样可以获取响应式值 */
	const { coast, msg } = toRefs(Son);
	defineExpose({
	  coast,
	  msg,
	});
	/* type_two 这样只能获得初始值 */
	/* defineExpose({
	  coast: Son.coast,
	  msg: Son.msg,
	}); */
	</script>

父组件

	<template>
	  <Son ref="sonRef" />
	</template>
	<script setup lang="ts">
	import Son from './Son.vue';
	const sonRef = ref();
	watch([() => sonRef?.value?.coast], () => {
	  /** type_one
	   *  🚀 >>> sonRef.value.coast 120
	   *  🚀 >>> sonRef.value.coast 121
	   *  🚀 >>> sonRef.value.coast 122
	   *  🚀 >>> sonRef.value.coast 123
	   *  🚀 >>> sonRef.value.coast 124
	   *  🚀 >>> sonRef.value.coast 125
	   */
	  console.log('🚀 >>> sonRef.value.coast', sonRef.value.coast);
	  /** type_two
	   *  🚀 >>> sonRef.value.coast 120
	   */
	});
	</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值