[問題] Vue3 defineProps的響應問題

作者: heavenbetula (綠草)   2024-04-16 15:16:51
想請問各位寫Vue3的大大
<script setup>
const props = defineProps();
const { name } = props;
/*
由於上行這樣寫會讓失去響應性,name如果更新,畫面不會更新
因此需改成:
const { name } = toRefs(props);
*/
</script>
<template>
<h1>Hello {{name}}</h1>
</template>
其中我有疑問的是如果原本會失去響應的寫法:
const props = defineProps();
const { name } = props;
改成 const { name } = defineProps();
就可以不用透過toRefs,也能正常動作
但不明白的是
const props = defineProps();
const { name } = props;

const { name } = defineProps();
不是一樣的寫法嗎?
為什麼結果會不一樣呢?
作者: ck574b027 (荒圍!定厝!賊!妹!)   2024-04-16 16:32:00
因為它只是macro。如果只有template會用到,最好寫成defineProps(['name'])
作者: ssccg (23)   2024-04-16 16:45:00
是你奇怪吧為什麼prop的欄位不寫在defineProps你另外寫一個 { name } 是想幹麻
作者: cloki (夜雲天)   2024-04-16 20:03:00
而且你寫法1那種本來就大概需要watch/computed才會響應吧
作者: ck574b027 (荒圍!定厝!賊!妹!)   2024-04-16 21:38:00
可以看看產出的js有何差別
作者: crazwade (crazwade)   2024-05-05 11:46:00
defineProps<{name: string}>(); 不用解構可以直接用name吧

Links booklink

Contact Us: admin [ a t ] ucptt.com