Vue class和style绑定

水深无声 2022-05-20 09:38 372阅读 0赞

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

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

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

  1. <template>
  2. <div class="hello" :class="{'active': isActive, 'error': isError}">
  3. </div>
  4. </template>
  5. <script> export default { name: 'HelloWorld', data() { return { isActive: true, isError: false } } } </script>
  6. <!-- Add "scoped" attribute to limit CSS to this component only -->
  7. <style scoped> </style>

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

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

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

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

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

  1. <template>
  2. <div class="hello" :class="hello_styles">
  3. </div>
  4. </template>
  5. <script> export default { name: 'HelloWorld', data() { return { hello_styles: { active: true, error: true } } } } </script>
  6. <!-- Add "scoped" attribute to limit CSS to this component only -->
  7. <style scoped> </style>

显示效果和上面一样。

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

  1. <template>
  2. <div class="hello" :class="hello_styles_comp">
  3. </div>
  4. </template>
  5. <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>
  6. <!-- Add "scoped" attribute to limit CSS to this component only -->
  7. <style scoped> </style>

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

2.数组语法

  1. <template>
  2. <div class="hello" :class="[activeClass,errorClass]">
  3. hello
  4. </div>
  5. </template>
  6. <script> export default { name: 'HelloWorld', data() { return { activeClass: 'active', errorClass: 'error' } } } </script>
  7. <!-- Add "scoped" attribute to limit CSS to this component only -->
  8. <style scoped> </style>

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,372人围观)

还没有评论,来说两句吧...

相关阅读

    相关 classstyle

      在数据绑定中,一个常见需求是,将数据与元素的 class 列表,以及元素的 style 内联样式的操作绑定在一起。由于它们都是属性(attribute),因此我们可以使用

    相关 Vue classstyle

    关于vue中class和style的绑定,我们在本篇主要是为大家说明一下该怎么使用v-bind来进行处理。 首先我们看下class的几种绑定方式: 1.对象语法 通过v