普通视图

发现新文章,点击刷新页面。
昨天 — 2025年12月30日首页

【博文精读】Chrome CSS 2025年回顾

2025年12月30日 11:12

本文由体验技术团队申君健原创。

序言

近日发现 Chrome 官方技术平台 chrome.dev 发布了一篇极具价值的 CSS 技术总结文章,原文链接为:CSS-Wrapped-2025,Wrapped 单词在这里是打包,总结,回顾的意思。Chrome官方罗列了2025年的新增CSS和组件特性等,有需要的小伙伴可以关注一下。此外,Chrome 官方亦发布了 2024 年度的 CSS 特性回顾文章,链接为:CSS-Wrapped-2024,可以对照查阅。

《CSS Wrapped 2025》一文共分为三个核心章节,分别是可定制的组件(Customizable Components)、 下一代交互(Next-gen Interactions)、 优化的人体工程学(Optimized ergonomics)。 由于精力时间有限,本文先精读第一部分,有机会再分享后续部分。

2025 全年,Chrome发布的版本为 132~143,本文的特性也集中在这个范围,它有很多全新的概念,或者是去年CSS概念的一些延伸。前端人员总不能第一时间使用新特性,以兼容性为借口忽视新技术,我也是一样。所以借此文章中新特性为提纲,全面总结该特性的知识,补充我的一些理解和总结。同时每一个新特性还准备一句话的解释完整示例,方便大家快速了解。Chrome 143升级好了吗,开始带你飞!

一、命令调用器 (Invoker Commands)

一句话的解释

命令调用器是通过Button元素,向Dialog,popover元素或任意元素上触发一个动作命令。 完整示例

命令调用器特性兼具声明式语法的高可读性优势,且能有效减少 JavaScript 代码的编写量。在该特性中,Button 元素被定义为 “命令源”,接收命令执行的元素则为 “命令目标”。

命令源:⭐仅 Button 元素才允许当命令源,它添加以下属性:

  • 【attr】commandfor: 属性值为命令目标元素的 id,用于关联对应的命令目标。
  • 【attr】command: 用于指定点击 Button 元素后触发的命令动作,其属性值说明如下:
命令 行为目标 等效js 备注
show-modal 打开dialog dialog.showModal()
close 关闭dialog dialog.close()
request-close 请求关闭dialog dialog.requestClose() 可取消: ev.preventDefault()
show-popover 打开popover el.showPopover()
hide-popover 关闭popover el.hidePopover()
toggle-popover 切换popover el.togglePopover()
--any-command 自定义命令 - 事件名必须 -- 打头
目标上监听command事件
非冒泡,可取消的事件
  • 【prop】command: 同上
  • 【prop】commandForElement: 同 commandfor ,值为HTMLElement对象。

命令目标: 通常是 dialog, popover元素,为它们添加一个事件:

  • 【event】command: 触发在目标元素上的事件。 其中事件参数 event.command 是命令值。

兼容性

支持chrome135+  ff144+, polyfill 方案

总结

  1. 该特性的核心价值不仅在于减少 JavaScript 代码量,更在于实现了更好的可读性,更好的语义化,更好的AI识别。Dialog元素是存在较久的冷门标签,Popover API是近两年的新特性,之前操作他们必须通过Javascript代码。
  2. 该特性也是一个微型的通知系统,某些程度上可以代替 new CustomEvent的使用。同样的,更好的可读性,参见图片翻转的示例。
  3. 命令源只能是Button,某种程度上限制了它的使用。

二、对话框轻量关闭(Dialog Light Dismiss)

一句话的解释

继 Popover Api 引入 Light Dismiss 之后,Dialog 也支持了它 完整示例

Light Dismiss 直接翻译就是轻量关闭,友好关闭,具体是指通过点击 ::backdrop 区域、按下 Esc 键即可触发目标元素自动关闭的交互行为。Light Dismiss同样的具备声明式可阅读性,还能避免Javascript的使用。

<dialog closedby="none">  不触发关闭 </dialog>
<dialog closedby="closerequest">接受 esc或其它js触发 </dialog>
<dialog closedby="any">  接受任何触发 </dialog>

Light Dismiss 通常是用户在交互过程中预期的默认行为,这一设计不仅体现了 Chrome 对用户使用体验人体工程学的关注,更彰显了其对开发者开发体验人体工程学的重视。开发者无需进行额外开发,即可获得预期的合理结果。延伸了解它的一些细节:

  • closerequest 与 any 的相比,它不接受点击::backdrop区域关闭;此外移动端的手指侧滑或导航回退也会触发closerequest的行为。
  • dialog.requestClose()在dialog元素上触发 cancel 和 close事件, 而dialog.close() 只触发close事件。 在cancel事件中执行ev.preventDefault()可阻止关闭。
  • dialog元素没有open事件,但它有 toggle, beforetoggle事件, 用来监听打开关闭。 事件对象的oldState,newState用来判断切换的方向。 此外,只有dialog 和 弹出层支持这2个事件名。

兼容性

支持chrome134+  ff141+, polyfill 方案

延伸理解 Popover API 的Light Dismiss

<button popovertarget="mypopover" popovertargetaction="toggle">切换显示</button>
<div id="mypopover" popover>这是一个 auto 弹出层</div>

命令源:⭐仅 Button 元素和Input(type=button)才允许当命令源,它添加以下属性:

  • 【attr】popovertarget: 其值为popover元素id
  • 【attr】popovertargetaction: 点击的命令动作,其值为: 'hide' | 'show' | 'toggle'

触发popover还可以用传统的Javascript, 或者Button的commands 模式,比如: el.showPopover()

popover层: 任意添加了 [popover] 属性的元素

  • 【attr】popover: 设置元素为一个弹出层,它最早支持以下2个值:
    • auto: 自动模式,也是默认值。 auto即符合Light Dismiss默认关闭行为。同一个页面上,auto类别的元素只能显示一个。
    • manual: 手动模式。必须显示的声明popovertargetaction,或调用Javascript函数才触发,比如:el.showPopover()。同一个页面上,manual类别元素可显示多个。

参考完整示例,对比 Dialog 与 Popover API :

  • 都支持Invoker Commands 和 Light Dismiss
  • 都支持Javascript控制和声明式表达: dialog元素的closedby 和 popover元素的popover属性
  • 都会产生一个Top Layer, 无须z-index就能置顶元素,且不受父元素的position影响。
  • 命令源和命令目标之间会隐式的产生aria-details关联aria-expanded,用于触发焦点导航等。

Popover API的这些特性兼容性为:chrome114+, ff125+

三、增强Popover (popover="hint") 与 兴趣调用(Interest Invoker)

一句话的解释

hint暗示:一种更轻量的触发行为的popover类别 完整示例

在上小节中,已经讲了popover原有的2个类别,今年它又新增了一个类别:hint 暗示。这种hint弹出层,不仅可以用原来的方法触发它,还增加了一种兴趣调用触发。 兴趣调用Interest Invoker是指:通过非点击事件,比如hover,mouseover,mouseout, focus,blur 它的变化。悬浮就显示,离开就隐藏,十分符合tooltip组件场景。

  <button interestfor="mypopover1">悬浮触发 hint1 弹出层</button>
  <div id="mypopover1" popover='hint'>这是一个 hint1 弹出层</div>

命令源:它新增以下相关内容:

  • 【attr】interestfor: 属性值为 hint类别的popover元素id
  • 【css-rule】interest-delay: 设置悬浮触发和离开隐藏的时间。 它是复合属性: interest-delay-start, interest-delay-end。默认触发的时间是 0.5s。
  • 【css-selector】 :interest-source 和 :interest-target 是指,如果当前兴趣正在发生,那么触发源和hint 弹出层就分别为具有上面的伪类。类似于 dialog打开时,dialog:open的伪类一样。详见上面示例。

hint 弹出层:新增以下事件:

  • 【event】interest: 触发显示的InterestEvent事件, 事件的source指向触发源元素。
  • 【event】loseinterest: 离开失去的InterestEvent事件,事件的source指向触发源元素。

兴趣调用与前面2节的内容有一些重要的差异:

  1. 强调必须非点击事件,场景对应“悬而未决”的状态,可以配合popover="hint"使用。
  2. 触发源更广泛,不仅是Button元素,还允许 <a>, <button>,<area>,SVG <a>
  3. hint类别不影响auto类别的弹窗,不会主动触发auto弹窗关闭。

长期以来Web标准对hover行为是淡视的,只有title属性和 :hover的伪类,一直缺少关键的hover事件。此次提供 interest事件,借此可以变相的视为一种hover事件

兼容性

支持chrome 142+, 不支持:ff,safari, polyfill 方案

四、可自定义的select (Customizable select)

一句话的解释

增强的select 和 option 元素,丰富的伪类、伪元素,定制更容易 完整示例

ScreenShot_20251230103200.PNG

可定制的select增加了很多dom规范和伪类,伪元素,内容太多不宜展开细述,感兴趣看上面的完整MDN示例,我已经增加详细的注释。此处仅列出一些重要的概念和事项,以便能快速理解:

  1. base-select 设置:

select 和 ::picker(select)伪元素都必须添加规则: appearance: base-select ,以区别于传统select样式。

  1. 弹出层::picker(select)特性:

它渲染在页面顶层Top Layer,这意味着它会显示在所有其他内容之上,不会被父容器裁剪。浏览器还会根据视口中的可用空间自动调整下拉列表的位置和翻转。

  1. 增强的option:

传统的option元素仅支持 label,value属性和selected,disabled的布尔属性。option中嵌套有其它元素,都是会忽略的

增强后的option元素支持嵌套span,img等等普通元素,但要避免嵌套 a, input 等交互元素就行了。 

  1. 新增 selectedcontent 元素:

该元素必须遵循 select > button > selectedcontent 的嵌套结构,详见示例。

select的选择值(即change事件)之后,选中的option的节点会被cloneNode创建副本,插入到selectedcontent中,所以他们结构一样,但不是同一个元素实例。

同时button是惰性的,不响应focus等,行为更像是 div

option 和 selectedcontent 的子项,都可以用普通的 css 选择器去分别控制样式。

  1. select 借用 Popover API

隐式借用了非常多的Popover 特性,比如 :popover-open伪类,无需anchor-name的隐式的锚点引用,且可以定义弹出层与锚点的位置关系,溢出翻转等等。

  1. select的multiple 和 optgroup 未增强

这意味着多选和分组功能,需要重新实现,对于组件库的作者来说,这无疑得回退到传统方案,幸好有Popover API。

兼容性:

支持 chrome 135+ , ff,safari均 不支持😭,polyfill 方案

这个方案并非真正意义的polyfill, 它使用自定义的 webComponent技术实现了平替。

五、滚动控制伪元素(::scroll-marker/button())

一句话的解释

为滚动容器的添加伪元素,用于控制容器滚动 完整示例

HTML早早添加了dialog, detail 等元素,但一直没有增加一个轮播图元素,今年只抠抠搜搜添加了三个伪元素,或许是因为添加一个新元素需要考虑的事情太多。

  1. ::scroll-button()  滚动容器按钮的伪元素,点击它会触发容器滚动。它非常类似于 ::before, ::after作用, 都需要content才显示,且呈现在容器的内部。

每个容器最多有4个滚动方向,括号的作用是指定滚动方向,可取值:*, left,right,up,down, block-end,block-start, inline-end,inline-start等。

按钮伪元素具有状态,比如容器滚动到两端之后,滚动按钮会自动禁用。 它具有以下状态: enabled, disabled,hover,active,focus

  1. ::scroll-marker 是滚动容器中,指示滚动项的伪元素,它同样也需要content才显示。

它具有 :target-current 伪类, 表示滚动到当前滚动项。当然, :hover, :active等伪类也能使用

  1. ::scroll-marker-group 是呈现在滚动容器内部的伪元素,收集容纳所有的::scroll-marker元素。

marker-group元素自身没有高度,但可以设置边框,布局,间距等内容。

兼容性:

支持chrome 135+ , ff,safari均 不支持😭。由于它是css 特性,无法Polyfill, 建议使用传统的div去实现即可!

六、设置滚动标记组容器(scroll-target-group)

一句话的解释

设置元素为滚动容器 完整示例

CSS属性 scroll-target-group 用来指定一个元素为滚动标记组容器, 它只有2个值: 

  • none: 元素非滚动标记组容器
  • auto: 元素为滚动标记组容器

滚动标记组容器中通常包含锚点链接列表等,配合伪类 :target-current 来突出显示某个锚点,效果非常类似传统的Anchor组件,当容器滚动时,可以高亮指定的目录项,不过这些都是浏览器自动完成的,不需要一行javascript。

它与::scroll-marker-group 有某些相似点:

  • ::scroll-marker-group:是在某个元素内部,创建一个伪元素容器,用来容纳::sroll-marker, 都是伪元素。
  • scroll-target-group: 是把一个真实元素变为滚动容器,内部放真实的link 类元素,所以控制上会更灵活。

从官方的态度看,这2个概念极其相近,都是定义了一个滚动容器,且内部的锚点行为一致,均支持伪类 :target-current 代表高亮状态,避免Javascript去滚动和设置高亮等。

兼容性:

支持 chrome 140+ ,但ff,safari均 不支持😭,且css 特性无法Polyfill。

七、锚定容器查询(Anchored Container Queries)

一句话的解释

锚点定位时,翻转状态可以查询完整示例

2024年的CSS回顾中,介绍了CSS锚点定位-—— anchor positioning, 实现类似 Tooltip组件的效果,让一个弹出层锚定到目标元素周围,且能自动翻转到适合位置,避免使用Javascript。 它的兼容性: chrome125+, safari26+, ff 不支持。

下面例子演示了:CSS锚点定位。tooltip会锚定在button的上下, 当滚动到边界时,会自动翻转显示。

.my-button {
  anchor-name: --my-btn-anchor; /* 定义一个名为 --my-btn-anchor 的锚点 */
}

.my-tooltip {
  position: absolute; /* 或 fixed */
  position-anchor: --my-btn-anchor; /* 关联到上面定义的锚点 */
  position-area: bottom;
  position-try-fallbacks: flip-block; 
}

思考一个问题:如果my-tooltip元素有小三角指示方向,那么简单的翻转后,小三角的位置怎么旋转呢? 答案是:定位元素无法意识(be aware)状态,小三角方向会错误。

此问题的解决方案即本次新增了CSS锚定容器查询能力,它通过指定tooltip的 container-type: anchored, 然后使用@container anchored 的查询语法,就让tooltip查询到,意识到自身的翻转状态(fallbacks 状态)。

.tooltip {
  container-type: anchored;

  /* 默认在下方, 小三角向上,位置在底部 */
  &::before {
    content: '▲';
    position: absolute;
    bottom: 100%;  
  }
}
/** 当容器查询到锚点变化 */
@container anchored(fallback: flip-block) {
  .tooltip::before {
    /* 小三角向下,并移到到顶部 */
    content: '▼';
    bottom: auto;
    top: 100%;  
  }
}

要讲明白锚点定位需要很大篇幅,且该示例复杂,大家可以转到官网查看示例。 目前 container-type: anchored 的文档连MDN上都没有,是比较新的概念。

container-type有效值:

  • normal: 元素不支持任何查询
  • size: 支持 inline 和 block 元素的尺寸的高度和宽度查询
  • inline-size: 仅支持 inline 元素的尺寸的宽度查询
  • scroll-state: 支持滚动态的偏移量和是否滚动到底等查询,chrome 133+, 但ff,safari均不支持
  • anchored: 锚点查询

兼容性:

container-type: anchored 支持 chrome 143+ ,但ff,safari均不支持😭,且css 特性无法Polyfill。

总结

通过以上种种新特性,可以看出chrome 不仅关注使用用户体验,更关注开发者体验。通过增加类似command属性,或者Light Dismiss的默认行为,以及滚动容器,滚动容器伪元素等技巧,让许多场景都可以无Javascript实现了。 不仅大大减少开发代码,还有极强的DOM可读性。

我目前从事于组件库开发。在组件库的开发时,所采用的技术通常是落后于浏览器最新技术的,理由就是为了兼容用户浏览器。比如 dialog 元素已经是广泛兼容,但目前仍没有见到哪个组件库使用它。通过这次梳理技术,感觉借助 dialog 以及 popover api 可以极大简化以往的组件开发,诸如:监听按键,计算z-index,计算弹出层位置,监听滚动进行位置跟随等等,这些是问题bug集中爆发区,现在基本都可以无Js代码的实现了。

另外,前面的诸多未广泛兼容的技术,大都有相应的Polyfill,尤其是属性,函数和事件的Polyfill基本都能找到。CSS的新伪类,伪元素虽然很难有Polyfill,但可以用添加类名的方案来兼容,辅助以一些Js事件就可以实现某种程度上的polyfill。oddbird.tech是一家服务公司,得到过Google的赞助,它们一直关注开发Popover APIAnchor positioning的兼容方案。这些方案都让我们以及早的使用新技术进行开发。

如果只需要支持最新的浏览器,前端的春天来了!

关于OpenTiny

欢迎加入 OpenTiny 开源社区。添加微信小助手:opentiny-official 一起参与交流前端技术~

OpenTiny 官网:opentiny.design
OpenTiny 代码仓库:github.com/opentiny
TinyVue 源码:github.com/opentiny/ti…
TinyEngine 源码: github.com/opentiny/ti…
欢迎进入代码仓库 Star🌟TinyEngine、TinyVue、TinyNG、TinyCLI、TinyEditor~ 如果你也想要共建,可以进入代码仓库,找到 good first issue 标签,一起参与开源贡献~

昨天以前首页

Vue2/Vue3 迁移头秃?Renderless 架构让组件 “无缝穿梭”

2025年12月26日 16:57

本文由体验技术团队刘坤原创。

"一次编写,到处运行" —— 这不是 Java 的专利,也是 Renderless 架构的座右铭!

开篇:什么是 Renderless 架构?

🤔 传统组件的困境

想象一下,你写了一个超棒的 Vue 3 组件:

<!-- MyAwesomeComponent.vue -->
<template>
  <div>
    <button @click="handleClick">{{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
const handleClick = () => {
  count.value++
}
</script>

问题来了:这个组件只能在 Vue 3 中使用!如果你的项目是 Vue 2,或者你需要同时支持 Vue 2 和 Vue 3,怎么办?

✨ Renderless 的解决方案

Renderless 架构将组件拆分成三个部分:

┌─────────────────────────────────────────┐
|             模板层(pc.vue)             |
|         "我只负责展示,不关心逻辑"        |
└─────────────────────────────────────────┘
              ↕️
┌─────────────────────────────────────────┐
│         逻辑层(renderless.ts)          │
│       "我是大脑,处理所有业务逻辑"         │
└─────────────────────────────────────────┘
              ↕️
┌─────────────────────────────────────────┐
│            入口层 (index.ts)           │
│         "我是门面,统一对外接口"          │
└─────────────────────────────────────────┘

核心思想:将 UI(模板)和逻辑(业务代码)完全分离,逻辑层使用 Vue 2 和 Vue 3 都兼容的 API。

📊 为什么需要 Renderless?

特性 传统组件 Renderless 组件
Vue 2 支持
Vue 3 支持
逻辑复用 困难 简单
测试友好 一般 优秀
代码组织 耦合 解耦

🎯 适用场景

  • ✅ 需要同时支持 Vue 2 和 Vue 3 的组件库
  • ✅ 逻辑复杂,需要模块化管理的组件
  • ✅ 需要多端适配的组件(PC、移动端、小程序等)
  • ✅ 需要高度可测试性的组件

第一步:理解 @opentiny/vue-common(必须先掌握)

⚠️ 重要提示:为什么必须先学习 vue-common?

在学习 Renderless 架构之前,你必须先理解 @opentiny/vue-common,因为:

  1. 它是基础工具:Renderless 架构完全依赖 vue-common 提供的兼容层
  2. 它是桥梁:没有 vue-common,就无法实现 Vue 2/3 的兼容
  3. 它是前提:不理解 vue-common,就无法理解 Renderless 的工作原理

打个比方vue-common 就像是你学开车前必须先了解的"方向盘、刹车、油门",而 Renderless 是"如何驾驶"的技巧。没有基础工具,再好的技巧也无法施展!

🤔 为什么需要 vue-common?

想象一下,Vue 2 和 Vue 3 就像两个说不同方言的人:

  • Vue 2this.$refs.inputthis.$emit('event')Vue.component()
  • Vue 3refs.inputemit('event')defineComponent()

如果你要同时支持两者,难道要写两套代码吗?当然不! 这就是 @opentiny/vue-common 存在的意义。

✨ vue-common 是什么?

@opentiny/vue-common 是一个兼容层库,它:

  1. 统一 API:提供一套统一的 API,自动适配 Vue 2 和 Vue 3
  2. 隐藏差异:让你无需关心底层是 Vue 2 还是 Vue 3
  3. 类型支持:提供完整的 TypeScript 类型定义

简单来说vue-common 是一个"翻译官",它让 Vue 2 和 Vue 3 能够"说同一种语言"。

🛠️ 核心 API 详解

1. defineComponent - 组件定义的统一入口

import { defineComponent } from '@opentiny/vue-common'

// 这个函数在 Vue 2 和 Vue 3 中都能工作
export default defineComponent({
  name: 'MyComponent',
  props: { ... },
  setup() { ... }
})

工作原理

  • Vue 2:内部使用 Vue.extend()Vue.component()
  • Vue 3:直接使用 Vue 3 的 defineComponent()
  • 你只需要写一套代码,vue-common 会自动选择正确的实现

2. setup - 连接 Renderless 的桥梁

import { setup } from '@opentiny/vue-common'

// 在 pc.vue 中
setup(props, context) {
  return setup({ props, context, renderless, api })
}

工作原理

  • 接收 renderless 函数和 api 数组
  • 自动处理 Vue 2/3 的差异(如 emitslotsrefs 等)
  • renderless 返回的 api 对象注入到模板中

关键点

// vue-common 内部会做类似这样的处理:
function setup({ props, context, renderless, api }) {
  // Vue 2: context 包含 { emit, slots, attrs, listeners }
  // Vue 3: context 包含 { emit, slots, attrs, expose }

  // 统一处理差异
  const normalizedContext = normalizeContext(context)

  // 调用 renderless
  const apiResult = renderless(props, hooks, normalizedContext)

  // 返回给模板使用
  return apiResult
}

3. $props - 通用 Props 定义

import { $props } from '@opentiny/vue-common'

export const myComponentProps = {
  ...$props, // 继承通用 props
  title: String
}

提供的基础 Props

  • tiny_mode:组件模式(pc/saas)
  • customClass:自定义类名
  • customStyle:自定义样式
  • 等等...

好处

  • 所有组件都有统一的 props 接口
  • 减少重复代码
  • 保证一致性

4. $prefix - 组件名前缀

import { $prefix } from '@opentiny/vue-common'

export default defineComponent({
  name: $prefix + 'SearchBox' // 自动变成 'TinySearchBox'
})

作用

  • 统一组件命名规范
  • 避免命名冲突
  • 便于识别组件来源

5. isVue2 / isVue3 - 版本检测

import { isVue2, isVue3 } from '@opentiny/vue-common'

if (isVue2) {
  // Vue 2 特定代码
  console.log('运行在 Vue 2 环境')
} else if (isVue3) {
  // Vue 3 特定代码
  console.log('运行在 Vue 3 环境')
}

使用场景

  • 需要针对特定版本做特殊处理时
  • 调试和日志记录
  • 兼容性检查

🔍 深入理解:vue-common 如何实现兼容?

场景 1:响应式 API 兼容

// 在 renderless.ts 中
export const renderless = (props, hooks, context) => {
  const { reactive, computed, watch } = hooks

  // 这些 hooks 来自 vue-common 的兼容层
  // Vue 2: 使用 @vue/composition-api 的 polyfill
  // Vue 3: 直接使用 Vue 3 的原生 API

  const state = reactive({ count: 0 })
  const double = computed(() => state.count * 2)

  watch(
    () => state.count,
    (newVal) => {
      console.log('count changed:', newVal)
    }
  )
}

兼容原理

  • Vue 2:vue-common 内部使用 @vue/composition-api 提供 Composition API
  • Vue 3:直接使用 Vue 3 的原生 API
  • 对开发者透明,无需关心底层实现

场景 2:Emit 兼容

export const renderless = (props, hooks, { emit }) => {
  const handleClick = () => {
    // vue-common 会自动处理 Vue 2/3 的差异
    emit('update:modelValue', newValue)
    emit('change', newValue)
  }
}

兼容原理

// vue-common 内部处理(简化版)
function normalizeEmit(emit, isVue2) {
  if (isVue2) {
    // Vue 2: emit 需要特殊处理
    return function (event, ...args) {
      // 处理 Vue 2 的事件格式
      this.$emit(event, ...args)
    }
  } else {
    // Vue 3: 直接使用
    return emit
  }
}

场景 3:Refs 访问兼容

export const renderless = (props, hooks, { vm }) => {
  const focusInput = () => {
    // vue-common 提供了统一的访问方式
    const inputRef = vm?.$refs?.inputRef || vm?.refs?.inputRef
    inputRef?.focus()
  }
}

兼容原理

  • Vue 2:vm.$refs.inputRef
  • Vue 3:vm.refs.inputRef
  • vue-common 提供统一的访问方式,自动适配

📊 vue-common 提供的常用 API 列表

API 作用 Vue 2 实现 Vue 3 实现
defineComponent 定义组件 Vue.extend() defineComponent()
setup 连接 renderless Composition API polyfill 原生 setup
$props 通用 props 对象展开 对象展开
$prefix 组件前缀 字符串常量 字符串常量
isVue2 Vue 2 检测 true false
isVue3 Vue 3 检测 false true

🎯 使用 vue-common 的最佳实践

✅ DO(推荐)

  1. 始终使用 vue-common 提供的 API
    // ✅ 好
    import { defineComponent, setup } from '@opentiny/vue-common'
    
    // ❌ 不好
    import { defineComponent } from 'vue' // 这样只能在 Vue 3 中使用
    
  2. 使用 $props 继承通用属性
    // ✅ 好
    export const props = {
      ...$props,
      customProp: String
    }
    
  3. 使用 $prefix 统一命名
    // ✅ 好
    name: $prefix + 'MyComponent'
    

❌ DON'T(不推荐)

  1. 不要直接使用 Vue 2/3 的原生 API
    // ❌ 不好
    import Vue from 'vue' // 只能在 Vue 2 中使用
    import { defineComponent } from 'vue' // 只能在 Vue 3 中使用
    
  2. 不要硬编码组件名前缀
    // ❌ 不好
    name: 'TinyMyComponent' // 硬编码前缀
    
    // ✅ 好
    name: $prefix + 'MyComponent' // 使用变量
    

🔗 总结

@opentiny/vue-common 是 Renderless 架构的基石

  • 🎯 目标:让一套代码在 Vue 2 和 Vue 3 中都能运行
  • 🛠️ 手段:提供统一的 API 和兼容层
  • 结果:开发者无需关心底层差异,专注于业务逻辑

记住:使用 Renderless 架构时,必须使用 vue-common 提供的 API,这是实现跨版本兼容的关键!

🎓 学习检查点

在继续学习之前,请确保你已经理解:

  • defineComponent 的作用和用法
  • setup 函数如何连接 renderless
  • $props$prefix 的用途
  • vue-common 如何实现 Vue 2/3 兼容

如果你对以上内容还有疑问,请重新阅读本节。理解 vue-common 是学习 Renderless 的前提!

第二步:核心概念 - 三大文件

现在你已经理解了 vue-common,我们可以开始学习 Renderless 架构的核心了!

📋 文件结构

一个标准的 Renderless 组件包含三个核心文件:

my-component/
├── index.ts          # 入口文件:定义组件和 props
├── pc.vue            # 模板文件:只负责 UI 展示
└── renderless.ts     # 逻辑文件:处理所有业务逻辑

1. 三大核心文件详解

📄 index.ts - 组件入口

import { $props, $prefix, defineComponent } from '@opentiny/vue-common'
import template from './pc.vue'

// 定义组件的 props
export const myComponentProps = {
  ...$props, // 继承通用 props
  title: {
    type: String,
    default: 'Hello'
  },
  count: {
    type: Number,
    default: 0
  }
}

// 导出组件
export default defineComponent({
  name: $prefix + 'MyComponent', // 自动添加前缀
  props: myComponentProps,
  ...template // 展开模板配置
})

关键点

  • $props:提供 Vue 2/3 兼容的基础 props
  • $prefix:统一的组件名前缀(如 Tiny
  • defineComponent:兼容 Vue 2/3 的组件定义函数

🎨 pc.vue - 模板文件

<template>
  <div class="my-component">
    <h1>{{ title }}</h1>
    <button @click="handleClick">点击了 {{ count }} 次</button>
    <p>{{ message }}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent, setup, $props } from '@opentiny/vue-common'
import { renderless, api } from './renderless'

export default defineComponent({
  props: {
    ...$props,
    title: String,
    count: Number
  },
  setup(props, context) {
    // 关键:通过 setup 函数连接 renderless
    return setup({ props, context, renderless, api })
  }
})
</script>

关键点

  • 模板只负责 UI 展示
  • 所有逻辑都从 renderless 函数获取
  • setup 函数是连接模板和逻辑的桥梁

🧠 renderless.ts - 逻辑层

// 定义暴露给模板的 API
export const api = ['count', 'message', 'handleClick']

// 初始化状态
const initState = ({ reactive, props }) => {
  const state = reactive({
    count: props.count || 0,
    message: '欢迎使用 Renderless 架构!'
  })
  return state
}

// 核心:renderless 函数
export const renderless = (props, { reactive, computed, watch, onMounted }, { emit, nextTick, vm }) => {
  const api = {} as any
  const state = initState({ reactive, props })

  // 定义方法
  const handleClick = () => {
    state.count++
    emit('update:count', state.count)
  }

  // 计算属性
  const message = computed(() => {
    return `你已经点击了 ${state.count} 次!`
  })

  // 生命周期
  onMounted(() => {
    console.log('组件已挂载')
  })

  // 暴露给模板
  Object.assign(api, {
    count: state.count,
    message,
    handleClick
  })

  return api
}

关键点

  • api 数组:声明要暴露给模板的属性和方法
  • renderless 函数接收三个参数:
    1. props:组件属性
    2. hooks:Vue 的响应式 API(reactive, computed, watch 等)
    3. context:上下文(emit, nextTick, vm 等)
  • 返回的 api 对象会被注入到模板中

第三步:实战演练 - 从零开始改造组件

现在你已经掌握了:

  • vue-common 的核心 API
  • ✅ Renderless 架构的三大文件

让我们通过一个完整的例子,将理论知识转化为实践!

🎯 目标

将一个简单的计数器组件改造成 Renderless 架构,支持 Vue 2 和 Vue 3。

📝 步骤 1:创建文件结构

my-counter/
├── index.ts          # 入口文件
├── pc.vue            # 模板文件
└── renderless.ts     # 逻辑文件

📝 步骤 2:编写入口文件

// index.ts
import { $props, $prefix, defineComponent } from '@opentiny/vue-common'
import template from './pc.vue'

export const counterProps = {
  ...$props,
  initialValue: {
    type: Number,
    default: 0
  },
  step: {
    type: Number,
    default: 1
  }
}

export default defineComponent({
  name: $prefix + 'Counter',
  props: counterProps,
  ...template
})

📝 步骤 3:编写逻辑层

// renderless.ts
export const api = ['count', 'increment', 'decrement', 'reset', 'isEven']

const initState = ({ reactive, props }) => {
  return reactive({
    count: props.initialValue || 0
  })
}

export const renderless = (props, { reactive, computed, watch }, { emit, vm }) => {
  const api = {} as any
  const state = initState({ reactive, props })

  // 增加
  const increment = () => {
    state.count += props.step
    emit('change', state.count)
  }

  // 减少
  const decrement = () => {
    state.count -= props.step
    emit('change', state.count)
  }

  // 重置
  const reset = () => {
    state.count = props.initialValue || 0
    emit('change', state.count)
  }

  // 计算属性:是否为偶数
  const isEven = computed(() => {
    return state.count % 2 === 0
  })

  // 监听 count 变化
  watch(
    () => state.count,
    (newVal, oldVal) => {
      console.log(`计数从 ${oldVal} 变为 ${newVal}`)
    }
  )

  // 暴露 API
  Object.assign(api, {
    count: state.count,
    increment,
    decrement,
    reset,
    isEven
  })

  return api
}

📝 步骤 4:编写模板

<!-- pc.vue -->
<template>
  <div class="tiny-counter">
    <div class="counter-display">
      <span :class="{ 'even': isEven, 'odd': !isEven }">
        {{ count }}
      </span>
      <small v-if="isEven">(偶数)</small>
      <small v-else>(奇数)</small>
    </div>

    <div class="counter-buttons">
      <button @click="decrement">-</button>
      <button @click="reset">重置</button>
      <button @click="increment">+</button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, setup, $props } from '@opentiny/vue-common'
import { renderless, api } from './renderless'

export default defineComponent({
  props: {
    ...$props,
    initialValue: Number,
    step: Number
  },
  emits: ['change'],
  setup(props, context) {
    return setup({ props, context, renderless, api })
  }
})
</script>

<style scoped>
.tiny-counter {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  text-align: center;
}

.counter-display {
  font-size: 48px;
  margin-bottom: 20px;
}

.counter-display .even {
  color: green;
}

.counter-display .odd {
  color: blue;
}

.counter-buttons button {
  margin: 0 5px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
}
</style>

🎉 完成!

现在这个组件可以在 Vue 2 和 Vue 3 中无缝使用了!

<!-- Vue 2 或 Vue 3 都可以 -->
<template>
  <tiny-counter :initial-value="10" :step="2" @change="handleChange" />
</template>

第四步:进阶技巧

恭喜你!如果你已经完成了实战演练,说明你已经掌握了 Renderless 架构的基础。现在让我们学习一些进阶技巧,让你的组件更加优雅和强大。

1. 模块化:使用 Composables

当逻辑变得复杂时,可以将功能拆分成多个 composables:

// composables/use-counter.ts
export function useCounter({ state, props, emit }) {
  const increment = () => {
    state.count += props.step
    emit('change', state.count)
  }

  const decrement = () => {
    state.count -= props.step
    emit('change', state.count)
  }

  return { increment, decrement }
}

// composables/use-validation.ts
export function useValidation({ state }) {
  const isEven = computed(() => state.count % 2 === 0)
  const isPositive = computed(() => state.count > 0)

  return { isEven, isPositive }
}

// renderless.ts
import { useCounter } from './composables/use-counter'
import { useValidation } from './composables/use-validation'

export const renderless = (props, hooks, context) => {
  const api = {} as any
  const state = initState({ reactive, props })

  // 使用 composables
  const { increment, decrement } = useCounter({ state, props, emit })
  const { isEven, isPositive } = useValidation({ state })

  Object.assign(api, {
    count: state.count,
    increment,
    decrement,
    isEven,
    isPositive
  })

  return api
}

2. 访问组件实例(vm)

有时候需要访问组件实例,比如获取 refs:

export const renderless = (props, hooks, { vm }) => {
  const api = {} as any

  const focusInput = () => {
    // Vue 2: vm.$refs.inputRef
    // Vue 3: vm.refs.inputRef
    const inputRef = vm?.$refs?.inputRef || vm?.refs?.inputRef
    if (inputRef) {
      inputRef.focus()
    }
  }

  // 存储 vm 到 state,方便在模板中使用
  state.instance = vm

  return api
}

3. 处理 Slots

在 Vue 2 中,slots 的访问方式不同:

export const renderless = (props, hooks, { vm, slots }) => {
  const api = {} as any
  const state = initState({ reactive, props })

  // 存储 vm 和 slots
  state.instance = vm

  // Vue 2 中需要手动设置 slots
  if (vm && slots) {
    vm.slots = slots
  }

  return api
}

在模板中检查 slot:

<template>
  <div v-if="state.instance?.$slots?.default || state.instance?.slots?.default">
    <slot></slot>
  </div>
</template>

4. 生命周期处理

export const renderless = (props, hooks, context) => {
  const { onMounted, onBeforeUnmount, onUpdated } = hooks

  // 组件挂载后
  onMounted(() => {
    console.log('组件已挂载')
    // 添加事件监听
    document.addEventListener('click', handleDocumentClick)
  })

  // 组件更新后
  onUpdated(() => {
    console.log('组件已更新')
  })

  // 组件卸载前
  onBeforeUnmount(() => {
    console.log('组件即将卸载')
    // 清理事件监听
    document.removeEventListener('click', handleDocumentClick)
  })

  return api
}

5. 使用Watch监听

export const renderless = (props, hooks, context) => {
  const { watch } = hooks

  // 监听单个值
  watch(
    () => state.count,
    (newVal, oldVal) => {
      console.log(`count 从 ${oldVal} 变为 ${newVal}`)
    }
  )

  // 监听多个值
  watch([() => state.count, () => props.step], ([newCount, newStep], [oldCount, oldStep]) => {
    console.log('count 或 step 发生了变化')
  })

  // 深度监听对象
  watch(
    () => state.user,
    (newUser) => {
      console.log('user 对象发生了变化', newUser)
    },
    { deep: true }
  )

  // 立即执行
  watch(
    () => props.initialValue,
    (newVal) => {
      state.count = newVal
    },
    { immediate: true }
  )

  return api
}

常见问题与解决方案

❓ 问题 1:为什么我的响应式数据不更新?

原因:在 renderless 中,需要将响应式数据暴露到 api 对象中。

// ❌ 错误:直接返回 state
Object.assign(api, {
  state // 这样模板无法访问 state.count
})

// ✅ 正确:展开 state 或明确暴露属性
Object.assign(api, {
  count: state.count, // 明确暴露
  message: state.message
})

// 或者使用 computed
const count = computed(() => state.count)
Object.assign(api, {
  count // 使用 computed 包装
})

❓ 问题 2:如何在模板中访问组件实例?

解决方案:将 vm 存储到 state 中。

export const renderless = (props, hooks, { vm }) => {
  const state = initState({ reactive, props })
  state.instance = vm // 存储实例

  return api
}

在模板中:

<template>
  <div>
    <!-- 访问 refs -->
    <input ref="inputRef" />
    <button @click="focusInput">聚焦</button>
  </div>
</template>
const focusInput = () => {
  const inputRef = state.instance?.$refs?.inputRef || state.instance?.refs?.inputRef
  inputRef?.focus()
}

❓ 问题 3:Vue 2 和 Vue 3 的 emit 有什么区别?

解决方案:使用 @opentiny/vue-common 提供的兼容层。

export const renderless = (props, hooks, { emit: $emit }) => {
  // 兼容处理
  const emit = props.emitter ? props.emitter.emit : $emit

  const handleClick = () => {
    // 直接使用 emit,兼容层会处理差异
    emit('update:modelValue', newValue)
    emit('change', newValue)
  }

  return api
}

❓ 问题 4:如何处理异步操作?

解决方案:使用 nextTick 确保 DOM 更新。

export const renderless = (props, hooks, { nextTick }) => {
  const handleAsyncUpdate = async () => {
    // 执行异步操作
    const data = await fetchData()
    state.data = data

    // 等待 DOM 更新
    await nextTick()

    // 此时可以安全地操作 DOM
    const element = state.instance?.$el || state.instance?.el
    if (element) {
      element.scrollIntoView()
    }
  }

  return api
}

❓ 问题 5:如何调试 Renderless 组件?

技巧

  1. 使用 console.log
export const renderless = (props, hooks, context) => {
  console.log('Props:', props)
  console.log('State:', state)
  console.log('Context:', context)

  // 在关键位置添加日志
  const handleClick = () => {
    console.log('Button clicked!', state.count)
    // ...
  }

  return api
}
  1. 使用 Vue DevTools
    • 在模板中添加调试信息
    • 使用 state 存储调试数据
  2. 断点调试
    • renderless.ts 中设置断点
    • 检查 api 对象的返回值

最佳实践

✅ DO(推荐做法)

  1. 模块化组织代码
    src/
    ├── index.ts
    ├── pc.vue
    ├── renderless.ts
    ├── composables/
    │   ├── use-feature1.ts
    │   └── use-feature2.ts
    └── utils/
        └── helpers.ts
    
  2. 明确声明 API
    // 在文件顶部声明所有暴露的 API
    export const api = ['count', 'increment', 'decrement', 'isEven']
    
  3. 使用 TypeScript
    interface State {
      count: number
      message: string
    }
    
    const initState = ({ reactive, props }): State => {
      return reactive({
        count: props.initialValue || 0,
        message: 'Hello'
      })
    }
    
  4. 处理边界情况
    const handleClick = () => {
      if (props.disabled) {
        return // 提前返回
      }
    
      try {
        // 业务逻辑
      } catch (error) {
        console.error('Error:', error)
        emit('error', error)
      }
    }
    

❌ DON'T(不推荐做法)

  1. 不要在模板中写逻辑

    <!-- ❌ 不好 -->
    <template>
      <div>{{ count + 1 }}</div>
    </template>
    
    <!-- ✅ 好 -->
    <template>
      <div>{{ nextCount }}</div>
    </template>
    
    const nextCount = computed(() => state.count + 1)
    
  2. 不要直接修改 props

    // ❌ 不好
    props.count++ // 不要这样做!
    
    // ✅ 好
    state.count = props.count + 1
    emit('update:count', state.count)
    
  3. 不要忘记清理资源

    // ❌ 不好
    onMounted(() => {
      document.addEventListener('click', handler)
      // 忘记清理
    })
    
    // ✅ 好
    onMounted(() => {
      document.addEventListener('click', handler)
    })
    
    onBeforeUnmount(() => {
      document.removeEventListener('click', handler)
    })
    

🎓 总结

Renderless 架构的核心思想是关注点分离

  • 模板层:只负责 UI 展示
  • 逻辑层:处理所有业务逻辑
  • 入口层:统一对外接口

通过这种方式,我们可以:

  • ✅ 同时支持 Vue 2 和 Vue 3
  • ✅ 提高代码的可维护性
  • ✅ 增强代码的可测试性
  • ✅ 实现逻辑的模块化复用

🚀 下一步

  1. 查看 @opentiny/vue-search-box 的完整源码
  2. 尝试改造自己的组件
  3. 探索更多高级特性

📚 参考资源

Happy Coding! 🎉

记住:Renderless 不是魔法,而是一种思维方式。当你理解了它,你会发现,原来组件可以这样写!

关于OpenTiny

欢迎加入 OpenTiny 开源社区。添加微信小助手:opentiny-official 一起参与交流前端技术~
OpenTiny 官网:opentiny.design
OpenTiny 代码仓库:github.com/opentiny
TinyVue 源码:github.com/opentiny/ti…
TinyEngine 源码: github.com/opentiny/ti…
欢迎进入代码仓库 Star🌟TinyEngine、TinyVue、TinyNG、TinyCLI、TinyEditor~ 如果你也想要共建,可以进入代码仓库,找到 good first issue 标签,一起参与开源贡献~

2025年OpenTiny年度人气贡献者评选正式开始

2025年12月25日 14:56

前言

携手共创,致敬不凡!

2025年,OpenTiny持续在前端开源领域扎根,每一位开发者都是推动项目共同前行的宝贵力量。从bug修复,到技术探讨;从参与开源活动,到输出技术文章;从使用项目,到参与共建,每一步跨越,都凝聚了开发者的智慧与汗水。 致敬所有在OpenTiny社区里默默付出、积极贡献、引领创新的杰出个人,我们正式启动“OpenTiny年度贡献者评选”活动!快为你喜爱的人气贡献者投票吧~

人气贡献者评选

名单公布:

新1.PNG

年度贡献者投票评选时间:

2025年12月25日-2025年12月31日

投票规则:

每人每天可回答3次,每次最多可投2票,最终投票结果选取前5名

投票入口:

wj.qq.com/s2/25333949…

去水印.png

关于OpenTiny

欢迎加入 OpenTiny 开源社区。添加微信小助手:opentiny-official 一起参与交流前端技术~
OpenTiny 官网:opentiny.design
OpenTiny 代码仓库:github.com/opentiny
TinyVue 源码:github.com/opentiny/ti…
TinyEngine 源码:github.com/opentiny/ti…
欢迎进入代码仓库 Star🌟TinyEngine、TinyVue、TinyNG、TinyCLI~ 如果你也想要共建,可以进入代码仓库,找到 good first issue标签,一起参与开源贡献~

❌
❌