Managing dynamic classes and styles is a fundamental part of building interactive interfaces. While requery-js `bind()` method can handle any attribute binding, class and style bindings often require more complex logic than simple string values. To make this easier, requery-js provides enhanced handling for class and style bindings that lets you work with objects and arrays directly, eliminating the need for manual string manipulation.
Written By Joel
Last updated About 1 month ago
Binding Classes
You can pass arrays containing strings for direct class names and objects for conditional classes. When using class bindings, existing static classes on the element are preserved and merged with the dynamic classes.
Binding Individual Classes
You can bind individual classes using the class.{name}
syntax:
defineComponent("my-component", {
props: {
max: 10
},
store: {
count: 0,
},
setup(component, props, store) {
component.query("button")
.bind("class.text-white", () => store.count >= props.max);
.bind("class.bg-red", () => store.count >= props.max);
}
})
Object Syntax
You can bind classes using an object where properties determine if a class should be applied:
defineComponent("my-component", {
props: {
max: 10
},
store: {
count: 0,
},
setup(component, props, store) {
component.query("button")
.bind("class", () => ({
'text-white': store.count >= props.max,
'bg-red': store.count >= props.max
}));
}
})
Array Syntax
You can also use an array that includes strings and objects with conditional classes:
defineComponent("my-component", {
props: {
max: 10
},
store: {
count: 0,
},
setup(component, props, store) {
component.query("button")
.bind("class", () => [
// Static class name
'foo',
// Conditional classes
{
'text-white': store.count >= props.max,
'bg-red': store.count >= props.max
}
]);
}
})
Bindings Inline Styles
You can bind inline styles using JavaScript objects:
defineComponent("my-component", {
store: {
theme: 'dark',
fontSize: 16
},
setup(component, props, store) {
component.query("element")
.bind("style", () => ({
color: store.theme === 'dark' ? '#333' : '#666',
fontSize: `${store.fontSize}px`
}));
}
})
Could not load article.
Could not load article.