Vue dynamically binds style styles to dynamically add style styles in multiple ways

The project will need to dynamically add the style inline style, and now point out several commonly used methods.

Notice:

1. All style attribute names with - must be changed to camel case, for example, font-size must be changed tofontSize。

2. In addition to the binding value, the values ​​of other attribute names should be enclosed in quotation marks, such as fontSize:'14px'not fontSize: 14px.

object form

//html
<div :style="{ color: '#333', fontSize: '14px' }"></div>

array form

//html
<div :style="[baseStyles, overridingStyles]"></div>

data(){
  return {
	baseStyles: {
	  width: '100px',
	  height: '100px'
	},
	overridingStyles: {
	  background: 'red',
	  height: '200px'
	}
  }
}

Ternary operator form

//html
<div :style="{background:index===0 ? '#FFFFFF' : '#000000'}"></div>

<div :style="[{color:index==0 ?'#333':'#000'},{fontSize:'14px'}]"></div>

Binding Computed Properties

//html
<div :style="setIconStyle"></div>

computed:{
//动态设置样式
etIconStyle() {
 return 'color: #333; fontSize: 14px'
 }
}

Bind styles by condition

//html
<div :style="setIconStyle(index)"></div>

computed:{
//动态设置样式
etIconStyle() {
 return function (index) {
	return index===0 ? 'color: #333' : 'color: #000'
  }
 }
}

Multiple values ​​(browser will choose based on running support)

//html
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

Guess you like

Origin blog.csdn.net/weixin_43743175/article/details/125274617