Vue can dynamically bind class names and styles through the v-bind directive. To bind a class name, use the v-bind:class directive to pass in an object or array. The true value in the object means that the corresponding class name is added to the element; to bind a style, use the v-bind:style directive to pass in the object and object key. Represents a CSS attribute, and the value represents the attribute value; the v-bind instruction can also pass in an array value, and each array element is an object or a string; when the bound data value changes, Vue will automatically update the class name or style of the element. Conveniently change the appearance of elements based on component state or user interaction.
Dynamic binding of Class and Style in Vue
In Vue, you can dynamically bind it by using the v-bind instruction Define the class name and style.
Bind class name
To dynamically bind the class name, you can use the v-bind:class
directive and pass in an object or array as value. If the value of the object is true, the corresponding class name will be added to the element.
<code class="html"><div v-bind:class="{ active: isActive }"></div></code>
In the above code block, if the value of isActive
is true, the active
class will be added to the <div>
element superior.
Binding style
To dynamically bind the style, you can use the v-bind:style
directive and pass in an object as the value. The object's keys represent CSS properties, and their values represent the property's value.
<code class="html"><div v-bind:style="{ color: 'red', fontSize: '20px' }"></div></code>
In the above code block, the color
attribute of the <div>
element will be set to red, and the font-size
attribute will be is set to 20 pixels.
Using array values
v-bind:class
and v-bind:style
instructions can also pass in arrays value. Each element in the array should be an object or string.
<code class="html"><div v-bind:class="[class1, class2]"></div> <div v-bind:style="[['color', 'red'], ['font-size', '20px']]"></div></code>
Response to data changes
When the bound data value changes, Vue will automatically update the class name or style of the element. This makes dynamic binding of class names and styles very convenient, as they can change the appearance of elements based on component state or user interaction.
The above is the detailed content of How to dynamically bind class and style in vue. For more information, please follow other related articles on the PHP Chinese website!