Skip to content

Commit 5afccf6

Browse files
author
Haew
committed
Bound get and set's elements
1 parent 508432d commit 5afccf6

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

packages/web/__tests__/web/cssVariables.spec.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,34 @@ describe("CSS variables", () => {
158158

159159
expect(variables.test.value).toBe("red");
160160
});
161+
162+
it("remembers bound element", async () => {
163+
const element = document.createElement("div");
164+
element.style.setProperty("--dummy-name", "red");
165+
let variables: UseCssVariables<Record<string, string>> = {} as any;
166+
167+
new Vue({
168+
template: "<div></div>",
169+
setup() {
170+
variables = useCssVariables({}, element);
171+
}
172+
}).$mount();
173+
174+
let { get, set } = variables;
175+
176+
// `get` should be bound to element
177+
expect(get("dummy-name")).toBe("red");
178+
179+
// `set` should be bound to element
180+
set("dummy-name", "blue");
181+
182+
// We check directly from the element to be sure
183+
expect(element.style.getPropertyValue("--dummy-name")).toBe("blue");
184+
185+
// We set that variable to another element
186+
set("dummy-name", "green", document.documentElement);
187+
188+
// Bound element should not have changed
189+
expect(element.style.getPropertyValue("--dummy-name")).toBe("blue");
190+
});
161191
});

packages/web/src/web/cssVariables.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export interface CssVariablesMethods {
2525
* @param name The CSS variable name.
2626
* @param element The element to get the variable for.
2727
*/
28-
get: (name: string, element: HTMLElement) => CssVariable;
28+
get: (name: string, el?: HTMLElement) => CssVariable;
2929

3030
/**
3131
* Sets the value of the given CSS variable for the given element.
@@ -34,7 +34,7 @@ export interface CssVariablesMethods {
3434
* @param value The CSS variable value.
3535
* @param element The element to set the variable for.
3636
*/
37-
set: (name: string, value: CssVariable, element: HTMLElement) => void;
37+
set: (name: string, value: CssVariable, el?: HTMLElement) => void;
3838
}
3939

4040
/**
@@ -131,10 +131,20 @@ export function useCssVariables<T extends CssVariableConfigurationObject>(
131131
// Stops on destroy
132132
onUnmounted(() => stop());
133133

134+
// Sets the `get` method
135+
const get = (name: string, el?: HTMLElement) => {
136+
return getVariableFor(name, el || element);
137+
};
138+
139+
// Sets the `set` method
140+
const set = (name: string, value: CssVariable, el?: HTMLElement) => {
141+
return setVariableFor(name, value, el || element);
142+
};
143+
134144
return {
135145
...result,
136-
get: getVariableFor,
137-
set: setVariableFor,
146+
get,
147+
set,
138148
resume: start,
139149
stop,
140150
listening

0 commit comments

Comments
 (0)