要啟用該語法,需要在 <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="check()" />
</template>
//子元件
<script setup lang="ts">
const emit = defineEmits(['change', 'delete'])
</script>