class和style绑定

落日映苍穹つ 2023-10-09 11:05 116阅读 0赞

在数据绑定中,一个常见需求是,将数据与元素的 class 列表,以及元素的 style 内联样式的操作绑定在一起。由于它们都是属性(attribute),因此我们可以使用 v-bind 来处理它们:只需从表达式中计算出最终的字符串。然而,处理字符串拼接,既麻烦又容易出错。为此,在使用 v-bind 指令来处理 classstyle 时,Vue 对此做了特别的增强。表达式除了可以是字符串,也能够是对象和数组。

与HTML的class绑定(Binding HTML Classes)

对象语法

v-bind:class 传入一个对象,来动态地切换 class:

  1. <div v-bind:class="{active: isActive}"></div>

上述语法意味着,active 这个 class 的存在与否,取决于 isActive 这个 data 属性的 truthy 值。  

这样,可以通过在对象中添加多个字段,来切换多个 class。此外,v-bind:class 指令也可以和普通 class 属性共存。所以,给定以下模板:

  1. <div class="static"
  2. v-bind:class="{active: isActive,'text-danger':hasError}">
  3. </div>  

然后,给定一下data:

  1. <body>
  2. <div class="static"
  3. v-bind:class="{active: isActive,'text-danger':hasError}">
  4. </div>
  5. <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  6. <script>
  7. var vm = new Vue({
  8. el: '.static',
  9. data: {
  10. isActive: true,
  11. hasError: false
  12. }
  13. })
  14. </script>
  15. </body>  

将会熏染为:

  1. <div class="static active"></div>

每当 isActivehasError 发生变化,class 列表就会相应地更新。例如,如果 hasError 值是 true,class 列表会变为 "static active text-danger"。  

绑定对象,也可以无需内联,而是外部引用 data:

  1. <div v-bind:class="classObject"></div>
  2. data: {
  3. classObject: {
  4. active: true,
  5. 'text-danger': false
  6. }
  7. }

(内联、外部引用)这两种方式的渲染结果相同。我们还可以将 class 和 style 与某个 computed 属性绑定在一起,此 computed 属性所对应的 getter 函数需要返回一个对象。这是一种常用且强大的用法:  

  1. <div v-bind:class="classObject"></div>
  2. data: {
  3. isActive: true,
  4. error: null
  5. },
  6. computed: {
  7. classObject: function () {
  8. return {
  9. active: this.isActive && !this.error,
  10. 'text-danger': this.error && this.error.type === 'fatal'
  11. }
  12. }
  13. }  

未完待续  

  

转载于:https://www.cnblogs.com/Black-rainbow/p/9362334.html

发表评论

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

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

相关阅读

    相关 classstyle

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

    相关 Vue classstyle

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