Vue class和style绑定

关于vue中class和style的绑定,我们在本篇主要是为大家说明一下该怎么使用v-bind来进行处理。

首先我们看下class的几种绑定方式:

1.对象语法
通过v-bind:class设置一个对象,可以动态的切换class。,在对象中我们可以传入多个属性。其中:class和普通的class是可以共同存在的。

<template>
  <div class="hello" :class="{'active': isActive, 'error': isError}">

  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        isActive: true,
        isError: false
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

我们运行程序,当然了我们的样式我没有写,这里只是给大家做个演示。
我们在浏览器中查看一下对应的html:
这里写图片描述

大家可以看到类名被替换为:class=”hello active”
这里我们说明一下:

其中类hello是普通类,这个是固定存在的。在后面的:class里面,active和error是我们需要根据我们数据来动态添加的。
我们拿active来说明,当active依赖的数据isActive为true时,div会拥有类名active,否则没有。所以后面的error类并未显示出来。

我们修改isError的值为true:
类名error就会增加到div的类名中去。
这里写图片描述

当然了,我们甚至可以直接把对象绑定到类名中去。

<template>
  <div class="hello" :class="hello_styles">

  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        hello_styles: {
          active: true,
          error: true
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

显示效果和上面一样。

另外,我们还可以绑定计算属性:

<template>
  <div class="hello" :class="hello_styles_comp">

  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        isActive: true,
        isError: 'failed'
      }
    },
    computed: {
      hello_styles_comp: function () {
        return{
          active: this.isActive && !this.isError,
          'text-fail': this.isError && this.isError === 'failed'
        }

      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

绑定语法和上面一样,不过在计算属性里面我们可以返回多个。

2.数组语法

<template>
  <div class="hello" :class="[activeClass,errorClass]">
    hello
  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        activeClass: 'active',
        errorClass: 'error'
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

这种场景是用于我们需要绑定多个类名的时候,我们可以讲一个数组应用于一个class列表。

当然了还有其他的方式,这里我们先简单说明一下,等我们后面碰到在说明。

另外,样式的绑定也是类似的。v-bind:style,这个大家可以参考着学习。

猜你喜欢

转载自blog.csdn.net/qingyulove/article/details/81070312