vue.js动态绑定:class和内联样式:style的几种方法
金蝶云社区-honey缘木鱼
honey缘木鱼
83人赞赏了该文章 3,929次浏览 未经作者许可,禁止转载编辑于2018年12月24日 09:37:27

Vue.js 的核心是一个响应的数据绑定系统,它允许我们在普通 HTML 模板中使用特殊的语法将 DOM “绑定”到底层数据。被绑定的DOM 将与数据保持同步,每当数据有改动,相应的DOM视图也会更新。基于这种特性,通过vue.js动态绑定class就变的容易。

 

一. 动态改变class的几种方式

思路:以某一页面样式需要单独适配iphonex为例

方式一.对象的形式(第一个参数 类名, 第二个参数:boolean值)  :class="{'footer':isIphoneX}" 

  //某一页面适配iPhone X
<div class="bottom" :class="{'footer':isIphoneX}">
</div>

 data () {
    return {
      isIphoneX:false
    }
  },

 mounted () {
    if(window.screen.width==375&&window.screen.height==812){
      this.isIphoneX = true
    }



渲染后的HTML:<div class="bottom footer"></div>

方式二.三元表达式(放在数组中,类名要用引号)  :class="[isIphoneX ? 'bottom' : 'footer']"

<div :class="[isIphoneX ? 'bottom' : 'footer']">

</div>

渲染后的HTML:<div class="footer"></div>


方式三.动态数组里的变量 :class="[isTrue, isFalse]"


<div :class="[{'footer':isIphoneX} , 'bottom']"></div>

渲染后和方法一是一样的。vue数据和class都符合双向绑定的规则!

                                                              


二.动态改变内联样式:style

    熟悉了以上动态绑定:class的语法后,很容易理解内联样式:style,下面以选项卡的为例


第一种:style的直接使用


<template>

  <div class="contain">

    <div v-for="(item,index) in headerList" v-on:click="selectMainTheme(index)" class="title">

     <a href="java:;" style="color: white;background:yellow">{{item.name}}</a>

    </div>

  </div>

</template>


第二种:单个属性


<a href="java:;" :style="{color:selColor}">{{item.name}}</a>

data(){

      return {

        selColor:'white',

      }

    }

第三种:驼峰写法

 <a href="java:;" :style="{'text-align':textAlign,fontSize: fontSize + 'px'}">{{item.name}}</a>

data(){

      return {

       textAlign: 'center',

      fontSize: 18,

      }

    }

'text-align' 或 fontSize//这里用引号也可用驼峰式


第四种:对象形式


<a href="java:;" :style="styleObj">{{item.name}}</a>

data () {

    return {

       styleObj:{

             display: 'inline-block',

            'text-align': 'center',//这里用引号也可用驼峰式

            background: 'red',

            fontSize: '14px',//这里用引号也可用驼峰式

            color: 'gold',

      },

  }

}

第五种:style的三元表达式

//选项卡是否选中,选中后改变样式

<template>

  <div class="contain">

    <div v-for="(item,index) in headerList" v-on:click="selectMainTheme(index)" class="title">

      <a href="java:;" :style="{'color':selIdx==index?'black':'white'}">{{item.name}}</a>

    </div>

  </div>

</template>


<script>

export default {

  name: 'home',

  data () {

    return {

      selIdx:0,

      selColor: 'white',

      headerList: [

        {name: '首页1'},

        {name: '首页2'},

        {name: '首页3'},

        {name: '首页4'},

        {name: '首页5'}

      ]

    }

  },

  methods: {

    selectMainTheme: function (index) 

      this.selIdx = index

    }

  }

}

</script>


注:如果style属性中带有中划线-,例如:font-sizebackground-color等等时,必须用驼峰写法或者是引号引起来,否则在渲染时会出错!



文章独发金蝶云社区






赞 83