In web development, we often encounter the need to dynamically change the style of an element, how to achieve it in VUE? The official website actually wrote very detailed, object syntax, array syntax and so on. I’ve summed up three approaches that individuals use most frequently in development
1. Class, ternary expression
Dynamically switch between two styles based on a ternary expression
:class="[item.isPlaying? 'playing' : ', 'drum-item ']"
Copy the code
2.:style= “XXXXX
Function:
:style="HandleStyle (second)"...... handleStyle(deg) { return { transform: "rotate(" + deg + "deg)"}; },Copy the code
Calculated attributes:
"Style =" imgStyle "...imgStyle() {
return {
padding: this.spacing + "px"}; },Copy the code
The two methods are very similar except that when you use the method, the view is refreshed and the function recalculates the value. If there is no change, it will not be evaluated, and will return the previous value directly
3. Use CSS variables to dynamically change styles by observing properties
For example, I now have a CSS variable like this
<input id="base" type="color" name="base" v-model="base" />
Copy the code
<span class="spantext">VUE.JS</span>
Copy the code
data: ()=> {
return {
base: '#ffff'}}Copy the code
.spantext {
color: var(--color);
}
Copy the code
Now listen for changes in base values by observing properties
watch: {
base: function(newValue, oldValue) { this.updateColor(); }},updateColor() {
this.$el.style.setProperty("--color", this.base);
}
Copy the code
At present, three kinds are summarized. If there is a new way, record again.