梗概

保持传入的响应式

外部传入的props在script setup中通过defineProps的props是一个响应式对象,需要解包的时候,需要使用Vue toRef方法进行解包

语法:

1. 在任意环境下(推荐):

<script setup>
const props = defineProps({//返回包含所有prop的对象, 用于在组合式api中使用
  foo: String,
  bar:{
	  type:String,
	  default:'lalala'
  }
})
const emit = defineEmits(['change', 'delete'])//返回包含所有emit的对象, 用于在组合式api中使用
/*setup code*/
</script>

2. 在typescript环境下(不推荐):

const props = withDefaults(defineProps<{
  foo: string
  bar?: number
}>(),{
	foo: 'default string!'
})
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()

3. 说明:

  • defineProps 接收与 props选项相同的值,defineEmits 也接收 emit选项相同的值。
  • ts与非ts的语法不能混用
  • 如果声明的props与data中的某个变量重名
    • 则data中的变量可以直接访问
    • props中的变量通过$props.变量访问