Vue dynamically modifies CSS style through style attribute and class attribute

Table of contents

Recap

Summarize

Summary of modifying class attributes

Modify the style attribute summary

Modify the class attribute

Modify the style attribute

Live time, super change


Recap

Requirements: Dynamically modify the style or class of a node according to some attributes of data

1. The first important point is v-bind: inside the quotation marks is a JS expression rather than a simple value or string. When judging, the truthy value is used instead of the Boolean value. In plain language, type conversion will be performed. Just treat it as the JS you wrote in the script tag (note the distinction between JS expressions and JS codes)

  • JS expression: generate a value, which can be placed anywhere a value is needed, and is very useful, such as ternary expressions, 1+'2', Math.max(a,b), methods with return values ​​in vue , computed, attributes in props , etc.
  • JS code (statement): such as if(x>1){...}

2. Another point is that you need to ensure that dynamic variables are managed by vue, can monitor changes, and go deep into the principle of responsiveness—Vue.js

If there is no dynamic update, please consider whether the data is responsive, browser support (some versions of IOS have problems), page rendering problems ($nexttick) and other factors.

Only then will the node re-render.

PS: Dynamic modification of class or Style will not conflict with native attributes, the effect is additive, you can write both statically and dynamically.

Summarize

As usual, let’s give a summary first, from the binding of Class and Style on the official website of Vue—Vue.js ’ workaround

Summary of modifying class attributes

<!-- 三目表达式判断,给的是类名-->
<div :class="isSquare?'square':'circular'"></div>

<div :class="[isChange?'blue':'red',isSquare?'square':'circular']"></div>

<!--布尔值-->
<div :class="{'square':isSquare,'square-color':isColor}"></div>

Modify the style attribute summary

<div class="square" :style="{'background-color':isChange?'blue':'red',
'color':isChange?'white':'black'}">测试</div>

<div class="square" :style="{'height':data_height+'px',
'width':data_width+'px'}">测试</div>

The summary is just to bring back memories for those who will meet. If you are new to it, or want to see more variants, please see the detailed explanation below.

Special Note: Note that the double quotes "" that must be included in the attribute have already been used, so the string in the double quotes can only use single quotes ' ', otherwise there will be a matching conflict.

Modify the class attribute

1. Use JS expressions to provide a string

<!--HTML部分 -->
<div :class="isSquare?'square':'circular'"></div>

<!--isSquare真值为真,等同于-->
<div class="square"></div>

<!--isSquare真值为假,等同于-->
<div class="circular"></div>

This method is used more often, you can change the content of the JS expression, and the final behavior you will have is not much different from the original operation, and the readability is better.

If more than one is needed, it will become an array (this behavior is not very standardized, and it is a bit strange, it is recommended to use the official method of vue below)

<div :class="[isChange?'blue':'red',isSquare?'square':'circular']"></div>

2. The object method provided by vue

Use the true value to judge whether to apply this class. Be careful not to use the abbreviation of the object key name , otherwise it is easy to make mistakes and it is inconvenient to observe. If there is a dash '-' in the key name, you must use the full string form, {'hello-class':'hello'}.

<!--HTML部分 -->
<div class="hello" :class="{'square':isSquare,'square-color':isColor}"></div>

<!--此时isSquare和isColor真值为真,等同于-->
<div class="hello square square-color"></div>
//data部分
data:{
   isSquare:true,
   isColor:1
}

Another point, don't forget that the key value of the object is also a JS expression, which means you can write like this

<!--HTML部分 -->
<div class="hello" :class="{'square':isSquare="是方的"?1:false,
'square-color':isColor}"></div>

<!--此时isSquare和isColor真值为真,等同于-->
<div class="hello square square-color"></div>
//data部分
data:{
   isSquare:'是方的',
   isColor:1
}

Is it blinding

3. Array object writing method

In fact, there is also an array containing objects, but in fact, multiple class names can be completed by one object. Objects are set in an array, which seems a bit farting. It depends on how you use it.

<!--HTML部分 -->
<div class="hello" :class="[{'square':isSquare},
{'square-color':isColor}]"></div>

<!--此时isSquare和isColor真值为真,等同于-->
<div class="hello square square-color"></div>

The purpose of a JS expression is to provide a value, which means you can use this value as a variable in data, which means you can also write the entire object/array in data.

<!--HTML部分 -->
<div :class="divObject"></div>
//data部分
data:{
   divObject:{
    'hello':true,
    'isSquare':true
   }
}

isn't it very simple

As long as it is a variant of the JS expression, it will not be displayed later, please adapt it yourself.

Modify the style attribute

1. How to write the object (the most recommended and most comfortable)

<!--HTML部分 -->
<div class="square" :style="{'background-color':isChange?'blue':'red',
'color':isChange?'white':'black'}">测试</div>

Attach a screenshot of vscode because the code block of csdn is really not very good-looking to see which are dynamic variables

77d35d6160084183a5826bdc588e4357.png

screenshot of vscode

Note! CSS property attribute names can be separated by camelCase or dashes (kebab-case, enclosed in quotation marks) 

Therefore, the following have the same effect, and the string after the ternary operator can also be replaced with the data in data.

<!--HTML部分 -->
<div class="square" :style="{backgroundColor:isChange?color_active:color_disactive,
color:isChange?textColor_active:textColor_disactive}">测试</div>

1b0d0c5d5cff431fb73de4deb92d65bf.png

screenshot of vscode

//date部分
data:{
   isChange:false,
   color_active:'blue',
   color_disactive:'red',
   textColor_active:'white',
   textColor_disactive:'black'
 }

2. Array object writing method

Similarly, like class, there is an array of package objects.

<!--HTML部分 -->
<div class="square" :style="[{'background-color':isChange?'blue':'red'},
{'color':isChange?'blue','red'}]"></div>
//date部分
data:{
   isChange:false,
   color_active:'blue',
   color_disactive:'red'
 }

Of course, you can also use JS expressions to write the corresponding object in data, so that the attributes are often more concise, and you can directly modify the attributes in the object. In this way, using JS to modify a certain Style attribute is different from directly modifying an entire class.

Live time, super change

After reading the above, everyone will find out, huh? Why doesn't the style attribute provide a string directly, of course it does.

<div class="container" :style="isSquare?'background-color:'blue'':''"></div>

Da da da, finished writing, well, matching error ! Remember what we said at the beginning, the problem of matching quotation marks. At this time, neither double quotation marks nor single quotation marks can express the blue string. And it is also very inconvenient to write the specified style.

So what should we do? At this time, template strings come in handy. Template strings are eventually parsed into strings, so this can also be treated as a JS expression.

<div class="container" :style="`background-color:${isChange?'pink':'orange'}`"></div>
<!-- 或者这样 -->
<div class="container" :style="'background-color:'+`${isChange?'pink':'orange'}`"></div>

The interpolation syntax ${} in the template string is also a JS expression like the interpolation syntax { {}} in the vue tag , which is to start nesting dolls.

Therefore, when there are multiple attributes, you can use template strings. Because objects are used, you need to pay attention to the way of writing colons that cannot be included in the string.

<div class="container" :style="{'background-color':`${isChange?'yellow':'green'}`,
'border-radius':`${isSquare?'50%':'0'}`}"></div>

The above code will prompt errors in some grammar checks, resulting in no code prompts for the following codes. It is not recommended to use, but it does not affect execution.

The time is almost here, let me share this first, and then continue to write when I think of something later. It is not easy to ask for a like for manual code words. If there is a mistake, you can modify it yourself.

Guess you like

Origin blog.csdn.net/weixin_43818307/article/details/125721619