vue3 setup lang=“ts“ defineExpose
●暴露reactive对象的时候可以将响应式对象转换为普通对象●不然父组件只能拿到初始值。
·
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>
更多推荐
已为社区贡献2条内容
所有评论(0)