From 03a9ea2b88df0842a820e09f7445c4b9189e3fcb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E7=99=BD=E9=9B=BE=E4=B8=89=E8=AF=AD?=
<32354856+baiwusanyu-c@users.noreply.github.com>
Date: Tue, 6 Aug 2024 23:33:57 +0800
Subject: [PATCH] feat(custom-element): support css `:host` selector by
applying css vars on host element (#8830)
close #8826
---
.../__tests__/helpers/useCssVars.spec.ts | 23 +++++++++++++++++++
.../runtime-dom/src/helpers/useCssVars.ts | 6 ++++-
2 files changed, 28 insertions(+), 1 deletion(-)
diff --git a/packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts b/packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
index 9f860a5e3c3..06b3e714132 100644
--- a/packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
+++ b/packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
@@ -4,6 +4,7 @@ import {
Suspense,
Teleport,
createStaticVNode,
+ defineCustomElement,
h,
nextTick,
reactive,
@@ -381,4 +382,26 @@ describe('useCssVars', () => {
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
}
})
+
+ // #8826
+ test('with custom element', async () => {
+ const state = reactive({ color: 'red' })
+ const container = document.createElement('div')
+ const App = defineCustomElement({
+ styles: [`div { color: red; }`],
+ setup() {
+ useCssVars(() => state)
+ return () => {
+ return h('div', 'hello')
+ }
+ },
+ })
+ customElements.define('css-vars-ce', App)
+ container.innerHTML = ``
+ document.body.appendChild(container)
+ await nextTick()
+ expect(container.innerHTML).toBe(
+ ``,
+ )
+ })
})
diff --git a/packages/runtime-dom/src/helpers/useCssVars.ts b/packages/runtime-dom/src/helpers/useCssVars.ts
index 286a4176076..8b47d55333c 100644
--- a/packages/runtime-dom/src/helpers/useCssVars.ts
+++ b/packages/runtime-dom/src/helpers/useCssVars.ts
@@ -38,7 +38,11 @@ export function useCssVars(getter: (ctx: any) => Record) {
const setVars = () => {
const vars = getter(instance.proxy)
- setVarsOnVNode(instance.subTree, vars)
+ if (instance.ce) {
+ setVarsOnNode(instance.ce as any, vars)
+ } else {
+ setVarsOnVNode(instance.subTree, vars)
+ }
updateTeleports(vars)
}