vue3 setup 语法糖写法

更新于 2023-09-17 20:58 53
专栏: 前端文章 标签: web vue

内容进行简化,仅作为参考,不要直接拷贝使用

子组件

  1. <script setup>
  2. let calendar;// 其他地方进行了赋值
  3. // 定义事件1
  4. const emit = defineEmits([
  5. 'onDateSelect',
  6. 'onEventClick',
  7. ])
  8. const onDateSelect=(selectInfo)=>{
  9. emit('onDateSelect',selectInfo)
  10. }
  11. const onEventClick=(selectInfo)=>{
  12. emit('onEventClick',selectInfo)
  13. }
  14. // 定义事件2
  15. const emit2 = defineEmits<{
  16. (e: 'done', info?: number): void
  17. }>()
  18. // 触发事件,针对定义事件2
  19. emit2("done",1)
  20. // 定义属性
  21. const props =defineProps({
  22. initialView:{
  23. type:String,
  24. default:"dayGridMonth",
  25. },
  26. dayMaxEvents:{
  27. type:[Boolean,Number],
  28. default:true,
  29. },
  30. })
  31. // 暴露出去的内容
  32. defineExpose({
  33. refetchEvents(){
  34. console.log("刷新")
  35. calendar.refetchEvents()
  36. }
  37. })
  38. </script>

父组件调用

  1. <template>
  2. <!-- 组件属性(使用冒号)、事件(使用@)、以及暴露接口的调用对象 -->
  3. <Calendar ref="calendarObj" @onDateSelect="handleDateSelect" @onEventClick="handleEventClick" />
  4. </template>
  5. <script setup>
  6. import { onMounted ,reactive,ref} from 'vue'
  7. let reactiveData=reactive({"display":false})
  8. // 事件
  9. const handleDateSelect=(selectInfo)=>{
  10. // 省略不少内容
  11. }
  12. // 事件
  13. function handleEventClick(clickInfo) {
  14. // 省略不少内容
  15. }
  16. // 组件内函数经过暴露调用
  17. const calendarObj=ref()
  18. // 或者这样写避免报错 ChildComponent:组件名字
  19. const calendarObj=ref<InstanceType<typeof ChildComponent>>(null)
  20. function testButton(){
  21. calendarObj.value.refetchEvents()
  22. }
  23. </script>

BLOG

搜索文章