# defineProps、defineEmits 要啟用該語法,需要在 <script> 代碼塊上添加```setup```attribute: ``` <script setup> console.log('hello script setup') </script> ``` ```defineProps```和 ```defineEmits``` 都是只能在 ```<script setup>``` 中使用的編譯器宏。他們不需要導入,且會隨著 ```<script setup>``` 的處理過程一同被編譯掉。 ## defineProps ``` defineProps ```接收與``` props ``` 選項相同的值,在父元件處使用子元件元件時,在元件加上傳遞至子元件的值或變數。 ``` //父元件 <template> <HelloWorld msg="Vite + Vue" /> //傳遞值 <HelloWorld :msg="msg" /> //傳遞變數 </template> //子元件 <script setup lang="ts"> const props = defineProps({ msg: String, }); </script> ``` ## defineEmits ``` defineEmits ```接收與``` emits ``` 選項相同的值,在子元件設定```defineEmits```,向父元件進行事件傳遞。 ``` <template> <HelloWorld @msg="change()" /> </template> //子元件 <script setup lang="ts"> const emit = defineEmits(['change', 'delete']) </script> ``` ## [範例](https://stackblitz.com/edit/vitejs-vite-9fl7hh?file=README.md) ## 參考 [Vite 官方文件](https://vitejs.dev/guide/) [Vue.js](https://vuejs.org/guide/introduction.html)