在VUE style中使用data中的變量的方法
最近項目中的公共組件,在復用的時候,針對不同的場景,需要不斷變更CSS里樣式的值,而且已經有了全局的公共組件樣式了
如果用vue傳統的動態綁定class和style的方式去修改樣式(文末會提到),需要額外寫很多變量和模塊class,那如果我的樣式的值,可以從父組件,傳到子組件,子組件根據傳入值去渲染對應樣式的值,其實就是要再style中使用data和props中的變量,這要怎么做呢?
其實很簡單,只需要三步,大家來看:
1、HTML結構
<Upload ref='upload' :show-upload-list='false' :before-upload='handleBeforeUpload' :disabled='disabled' :max-size='maxSize' action>
2、作用區域范圍內設置“CSS變量”
<style lang='less' scoped>.info-img-wrap { --textAlignPosition: center; /deep/ .ivu-upload { text-align: var(--textAlignPosition); }}<style/>
3、在JS中通過setProperty()方法修改“--textAlignPosition”的值,從而間接改變對應子元素的(text-align)文本對齊方式
mounted() { this.$nextTick(function () { this.$refs.upload.$el.style.setProperty( ’--textAlignPosition’, this.textAlign ); });}
這要就完成了。
下面再復習一下vue中修改樣式還有另外兩種方法,1是動態修改class,2是動態修改style
1、vue中可以通過對象語法和數組語法來修改class
對象語法
html
<div v-bind:class='{ ’active’: isActive, ’text-danger’: hasError }'></div>
js
data: { isActive: false, hasError: true}
數組語法
html
<div v-bind:class='[isActive ? activeClass : ’’, errorClass]'></div>
js
data: { isActive: false, hasError: true, activeClass: ’active’, errorClass: ’text-danger’}
只需要動態改變isActive和hasError的值,就可以實現div的綁定不同的class和去掉綁定
2、vue中可以通過對象語法和數組語法來修改style
對象語法
html
<div v-bind:style='{ color: activeColor, fontSize: fontSize + ’px’ }'></div>
js
data: { activeColor: ’red’, fontSize: 30}
數組語法
html
<div v-bind:style='[styleColor, styleSize]'></div>
js
data: { styleColor: { color: ’red’ }, styleSize:{ fontSize:’23px’ }}
只要改變data中的變量styleColor和styleSize,就可以動態修改div的style了。
到此這篇關于在VUE style中使用data中的變量的方法的文章就介紹到這了,更多相關VUE style使用data變量內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
