]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
wip: support set style vars on custom element
authordaiwei <daiwei521@126.com>
Mon, 10 Nov 2025 08:30:12 +0000 (16:30 +0800)
committerdaiwei <daiwei521@126.com>
Mon, 10 Nov 2025 08:45:24 +0000 (16:45 +0800)
packages/runtime-vapor/__tests__/helpers/useCssVars.spec.ts
packages/runtime-vapor/src/helpers/useCssVars.ts

index 1352760d1371a65e30a0c424f06cb47ee7400c89..66f56c6752b69e9f612ad0572582d855318c29a2 100644 (file)
@@ -1,7 +1,9 @@
 import {
   createComponent,
   createIf,
+  createPlainElement,
   defineVaporComponent,
+  defineVaporCustomElement,
   renderEffect,
   setStyle,
   template,
@@ -237,7 +239,29 @@ describe('useVaporCssVars', () => {
     }
   })
 
-  test.todo('with custom element', async () => {})
+  test('with custom element', async () => {
+    const state = reactive({ color: 'red' })
+    const CE = defineVaporCustomElement({
+      setup() {
+        useVaporCssVars(() => state)
+        return template('<div>hello</div>', true)()
+      },
+    })
+
+    customElements.define('css-vars-ce', CE)
+
+    const { html } = define({
+      setup() {
+        return createPlainElement('css-vars-ce', null, null, true)
+      },
+    }).render()
+
+    expect(html()).toBe('<css-vars-ce style="--color: red;"></css-vars-ce>')
+
+    state.color = 'green'
+    await nextTick()
+    expect(html()).toBe('<css-vars-ce style="--color: green;"></css-vars-ce>')
+  })
 
   test('should set vars before child component onMounted hook', () => {
     const state = reactive({ color: 'red' })
index 9a67ae6bfd0e0a9a00aba891cd7bd899e4dc16a7..a807ffa27400a897efa66d87512f200a73c4a0c0 100644 (file)
@@ -1,4 +1,5 @@
 import {
+  type GenericComponentInstance,
   baseUseCssVars,
   currentInstance,
   setVarsOnNode,
@@ -14,7 +15,7 @@ export function useVaporCssVars(getter: () => Record<string, string>): void {
     instance,
     () => resolveParentNode(instance.block),
     getter,
-    vars => setVarsOnBlock(instance.block, vars),
+    vars => setVars(instance, vars),
   )
 }
 
@@ -30,6 +31,17 @@ function resolveParentNode(block: Block): Node {
   }
 }
 
+function setVars(
+  instance: VaporComponentInstance,
+  vars: Record<string, string>,
+): void {
+  if ((instance as GenericComponentInstance).ce) {
+    setVarsOnNode((instance as GenericComponentInstance).ce as any, vars)
+  } else {
+    setVarsOnBlock(instance.block, vars)
+  }
+}
+
 function setVarsOnBlock(block: Block, vars: Record<string, string>): void {
   if (block instanceof Node) {
     setVarsOnNode(block, vars)