• vue3 script setup写法


    公司代码扫描要求一个函数不能超过50行,那么一般vue3写法setup函数肯定超了,又懒得写到hooks,同事介绍了去年vue3出的新的语法糖,研究了下,写篇博客

    简单的将,去掉了exprot defult这个壳子,然后也不需要写return了,props和emit写法变成如下

    const props = defineProps({
      data: {
        type: Object,
        default: () => ({}),
      },
    });
    const emit = defineEmits(['close']);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    后面的方法直接引用即可,如props.data,emit(‘close’);

    还有删掉了components,import引入的组件不需要在这里声明了,可以直接用
    如果组件是异步调用进来,改成如下

    const XXXDialog = defineAsyncComponent(() => import('./XXX-dialog.vue'));
    
    • 1

    注意如果之前的写法,父组件直接调用子组件的ref,用这种写法会获取不到子组件的信息,需要在子组件加如下

    const info = ref([]);
    defineExpose({
      info
    })
    
    • 1
    • 2
    • 3
    • 4

    需要通过ref读的信息丢到defineExpose里面

    完整版如下

    <template>
     //html代码
    </template>
    
    <script setup lang="ts">
    import { ref, watchEffect, reactive, computed, defineProps, defineEmits } from 'vue';
    const XXXDialog = defineAsyncComponent(() => import('./XXX-dialog.vue'));
    
    const props = defineProps({
      data: {
        type: Object,
        default: () => ({}),
      },
    });
    const emit = defineEmits(['close', 'submit']);
    //后面是交互逻辑
    const onCancel = () => {
      emit('close');
    };
    </script>
    
    <style lang="scss" scoped>
    //样式
    </style>
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    总体来说写的代码变少了,所有代码都在script里面。
    最后附上学习的几个链接:
    https://zhuanlan.zhihu.com/p/471806345
    https://blog.csdn.net/qq_41880073/article/details/124199104
    https://blog.csdn.net/weixin_43931876/article/details/120058286

  • 相关阅读:
    Docker定时删除none镜像
    Jmeter性能 —— 事务控制器
    浙大计算机研究生复试上机考试-2005年畅通工程(考察并查集)
    vim YouCompleteMe报错:version `GLIBCXX_3.4.20‘ not found 解决方法
    边缘计算AI智能安防监控视频平台车辆违停算法详解与应用
    66个Python练手项目,附源码
    达梦集群搭建
    maven 进阶
    第七章 用户和组管理
    设计模式-代理模式
  • 原文地址:https://blog.csdn.net/wnk1997/article/details/126985841