Hello World!|

feixianxing

园龄:2年8个月粉丝:31关注:1

2023-02-17 14:11阅读: 432评论: 0推荐: 0

[Vue3] defineExpose要在方法声明定义以后使用

[Vue3] defineExpose要在方法声明定义以后使用

Vue3中的setup默认是封闭的,如果要从子组件向父组件暴露属性和方法,需要用到defineExpose.

defineProps, defineEmits一样,这三个函数都是内置的,不需要import.

不过defineProps, defineEmits都会返回一个实例,而defineExpose是无返回值的.

const props = defineProps({})
const emit = defineEmits([])
defineExpose({})

defineExpose的使用

子组件Child.vue

<template>
	{{ name }}
</template>

<script setup>
import { ref } from 'vue'

const name = ref("Nicholas.")
const sayName = ()=>{
    console.log("my name is "+name.value)
}

defineExpose({
	name,
	sayName
});
</script>

父组件Father.vue

<template>
	<Child ref="child"></Child>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const child = ref(null)
onMounted(()=>{
    console.log(child.value.name)	// "Nicholas"
    child.value.sayName()			// "my name is Nicholas"
})
</script>

总结

  1. 向外暴露的时候变量会自动解包,比如上面子组件的name:ref<String>暴露到父组件的时候自动变成了name:String.

  2. 注:defineExpose一定要在变量和方法声明定义之后再使用。

    不知道以后会不会有修改,不过在2023/02/17,如果defineExpose写在变量和函数前面,那么浏览器的控制台会输出很多警告,并且最终将该页面卡死。

屏幕截图 2023-02-17 140231

本文作者:feixianxing

本文链接:https://www.cnblogs.com/feixianxing/p/define-expose-used-after-the-method-declaration-definition.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   feixianxing  阅读(432)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起