Since V-bind can dynamically bind the properties of a tag, you can also use V-bind to work with class and style, just to calculate the final string of the expression. However, string concatenation is troublesome and error-prone. Therefore, when V-bind is used for class and style, vue.js specifically enhances it. The result type of an expression, in addition to a string, can be an object or an array- bound HTML Class: object Syntax:
We can pass to v-bind:class an object to dynamically switch class, the object's property name is the class name to add to the tag, and determines whether the class is to display the key value is true or FALSE, where the key value can be either an expression or data
The above syntax indicates that the classactive update will depend on whether the data property isActive is True
If the return result of the dynamic calculation function Currentinde is equal to the value of index, the class current is displayed.
We can also pass in more properties in the object to dynamically switch multiple classes. In addition, the V-bind:class directive can coexist with normal class attributes
The following data:
Render as:
You can also bind directly to an object in the data:
array Syntax:
We can pass an array to V-bind:class to apply a class list, the value of the array is not to be added to the tag, but its corresponding value in data is actually added to the DOM
Render as:
If you also want to switch the class in the list according to the criteria, you can use the ternary expression:
This example always adds Errorclass, but only when isActive is true Activeclass
However, this is tedious to write when there are multiple criteria class. Object syntax can be used in array syntax
used on the component:
When you use the class attribute on a custom component, these classes will be added to the root element, and the existing class on that element will not be overwritten by a way of declaring the component through "vue.component ()"
For example, if you declare this component:
And then add some classes when you use it.
HTML will eventually be rendered as
The same applies to binding HTML class
When IsActive is true, the HTML will be rendered as
binding inline styles: Object Syntax:
V-bind:style's object syntax is very intuitive-looking very much like CSS, it's actually a JavaScript object. CSS property names can be named with Hump (CamelCase) or short-cross (kebab-case)
Binding directly to a style object is usually better, making the template clearer
array Syntax:
V-bind:style array syntax to apply multiple style objects to an element