当前位置: 首页 > news >正文

Vue 组件定义方式的区别

原始写法(函数式组件)
在 Vue 3 中,​​render 是保留属性名​​,与组件的渲染逻辑直接相关。即使未显式声明:如果父组件传递了 render 属性,Vue 会优先将其注入到 props 中(类似 key、ref 等内置属性)。
​​这是 Vue 的内部优化​​,确保渲染函数能直接访问。
import { h } from 'vue'const Render = (props, ctx) => {return props.render ? h(props.render, ctx.attrs, ctx.slots) : ''
}传递props
import { h, defineProps } from 'vue'const RenderComponent = (props) => {const { render, ...rest } = defineProps({render: {type: Function,required: true},scope: {type: Object,default: () => ({})}})return render ? h(render, rest) : null
}export default RenderComponent
export default Render
新写法(使用 defineComponent)
import { defineComponent } from 'vue'export default defineComponent({props: ['render'],setup(props, ctx) {return () => props.render ? h(props.render, ctx.attrs, ctx.slots) : ''}
})

主要区别

  1. 组件类型
    ​​原始写法​​:函数式组件(Functional Component)
    无状态(无 this)
    无实例生命周期
    性能略高(Vue 3 中差异变小)
    ​​新写法​​:标准组件(使用 defineComponent)
    有组件实例
    完整的生命周期
    可以使用 Composition API 的全部功能
  2. Props 声明
    ​​原始写法​​:隐式接收 props
    所有属性都通过 props 参数接收
    没有显式的 props 验证
    ​​新写法​​:显式声明 props
    通过 props 选项明确声明
    可以添加类型验证和默认值
  3. 渲染机制
    ​​原始写法​​:直接返回渲染结果
    函数体本身就是渲染函数
    ​​新写法​​:通过 setup 返回渲染函数
    setup 返回一个函数(工厂函数)
    每次重新渲染都会调用这个工厂函数
  4. 上下文访问
    ​​原始写法​​:通过第二个参数 ctx 访问
    包含 attrs、slots 和 emit
    ​​新写法​​:通过 setup 的第二个参数访问
    同样包含 attrs、slots 和 emit
    但组织方式更符合 Composition API 风格
  5. TypeScript 支持
    ​​原始写法​​:类型推断有限
    ​​新写法​​:更好的 TypeScript 集成
    可以明确指定 props 类型
    更好的编辑器支持
http://www.lqws.cn/news/479323.html

相关文章:

  • Rabbitmq集成springboot 使用死信队列
  • day 39 打卡
  • 10-K 和 10-Q是什么?
  • MySQL基础函数篇
  • DubboSPI
  • 如何在FastAPI中玩转GitHub认证,让用户一键登录?
  • 安卓对外发布工程源码:怎么做到仅UI层公布
  • Openwrt基本初始化(安装中文包,磁盘扩容)
  • MATLAB的.mat文件
  • Python 商务数据分析—— NumPy 学习笔记Ⅱ
  • Spark教程1:Spark基础介绍
  • 爬虫入门练习(文字数据的爬取)
  • Vue3解析Spring Boot ResponseEntity
  • “MOOOA多目标鱼鹰算法在无人机多目标路径规划
  • 2025国际无人机应用及防控大会四大技术专题深度解析
  • 算法-动态规划-钢条切割问题
  • 理解后端开发中的中间件(以gin框架为例)
  • Android14 app被冻结导致进程间通信失败
  • 一键打包利器:gopack - 极简Go程序编译与压缩工具
  • 解决OSS存储桶未创建导致的XML错误
  • 【CBAP50技术手册】#44 Survey and Questionnaire(问卷调研):BA(业务分析师)的“信息入口”
  • 反无人机系统:技术利刃如何守护低空安全?
  • 【2025年软考中级】第三章数据结构3.4 数组与矩阵
  • 计算鱼眼相机的内参矩阵和畸变系数方法
  • 开源 python 应用 开发(二)基于pyautogui、open cv 视觉识别的工具自动化
  • linux VFS简介
  • Java面试复习:基础、面向对象、多线程、JVM与Spring核心考点
  • 历史数据分析——山西汾酒
  • Linux下QGIS二次开发环境搭建
  • React 核心原理与Fiber架构