[問題] Vue3 defineProps的響應問題

看板Web_Design作者 (綠草)時間1周前 (2024/04/16 15:16), 1周前編輯推噓1(105)
留言6則, 3人參與, 1周前最新討論串1/1
想請問各位寫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(); 不是一樣的寫法嗎? 為什麼結果會不一樣呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.68.234.131 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Web_Design/M.1713251813.A.E0E.html

04/16 16:32, 1周前 , 1F
因為它只是macro。如果只有template會用到,最好寫成
04/16 16:32, 1F

04/16 16:32, 1周前 , 2F
defineProps(['name'])
04/16 16:32, 2F
喔不好意思,原本想說簡化一下寫法來描述問題,所以寫不完整 沒說明清楚我是使用typescript 原始寫法是這樣的: interface Props { name: string; } //寫法1 const props = defineProps<Props>(); const { name } = props; //寫法2 const { name } = defineProps<Props>(); 一直以為這兩種寫法是相等的 但對於響應式的結果是不同的 寫法1無法響應 寫法2可以響應

04/16 16:45, 1周前 , 3F
是你奇怪吧為什麼prop的欄位不寫在defineProps
04/16 16:45, 3F

04/16 16:48, 1周前 , 4F
你另外寫一個 { name } 是想幹麻
04/16 16:48, 4F
※ 編輯: heavenbetula (219.68.234.131 臺灣), 04/16/2024 17:12:34

04/16 20:03, 1周前 , 5F
而且你寫法1那種本來就大概需要watch/computed才會響應吧
04/16 20:03, 5F

04/16 21:38, 1周前 , 6F
可以看看產出的js有何差別
04/16 21:38, 6F
痾...後來發現是vue版本的處理,在3.4版本後上述寫法2可以響應,但測試3.2版本 上述寫法2是不可以響應的 ※ 編輯: heavenbetula (219.68.234.131 臺灣), 04/17/2024 02:06:39
文章代碼(AID): #1c7YNbuE (Web_Design)
文章代碼(AID): #1c7YNbuE (Web_Design)