vue动态绑定内联样式(v-bind:style)

发布时间 2023-03-27 09:31:51作者: 会转圈圈的哆瑞米

一、对象语法

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

  data() {
    return {
      activeColor: 'red',
      fontSize: 30
    }
  }

<div :style="styleObject"></div>

data() {
  return {
    styleObject: {
      color: 'red',
      fontSize: '13px'
    }
  }
}
<div :style="boxStyle"></div>
<button  @click="change" type="button">改变Box大小</button>

    
            data(){
                return{
                    boxWidth:'100px',
                    boxheight:'100px',
                    boxBorder:'1px solid red'
                }
            },
            methods:{
                change(){
                    this.boxWidth = '200px',
                    this.boxheight = '200px',
                    this.boxBorder = '2px solid black'
                },
            },
            computed:{
                boxStyle(){
                    return{
                        width:this.boxWidth,
                        height:this.boxheight,
                        border:this.boxBorder
                    }
                }
            },

二、数组语法

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

三、自动添加前缀

// 在 :style 中使用需要 (浏览器引擎前缀) vendor prefixes 的 CSS property 时,如 transform,Vue 将自动侦测并添加相应的前缀。

四、多重值

// 只会渲染数组中最后一个被浏览器支持的值。在本例中,如果浏览器支持不带浏览器前缀的 flexbox,那么就只会渲染 display: flex。
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>