【Vue.js】类与样式的绑定

74 阅读2分钟

前置知识:

1. v-bind

1.1. 概述:

v-bind 是一个 Vue 的内置指令,主要的作用就是在标签上绑定属性

1.2. 基本使用:

在模板视图中动态绑定属性,我们需要使用 v-bind指令进行绑定:

export default {
  data() {
    return {
      attr: 'a'
    };
  },

  template: `
    <div v-bind:data-attr="attr">
      Hello
    </div>
  `
};

但是,这样写似乎有点麻烦,我们可以只写使用它的语法糖 :把上述的代码改写一下:

export default {
  data() {
    return {
      attr: 'a'
    };
  },

  template: `
    <div :data-attr="attr"> <!-- <div v-bind:data-attr="attr"> -->
      Hello
    </div>
  `
};

2. 常见命名法

命名法英文名命名法中文名命名法举例使用场景
camelCase小驼峰命名法helloWorldjs变量名 方法名 ...
kebab-case短横线命名法hello-worldspinal-case 对象的属性名, CSS常规类名(BEM规范) ...
snake_case蛇形命名法hello_world大写的常量 (ERROR_TYPE, BASE_URL)、枚举、(python)
PascalCase大坨峰命名法HelloWorld构造函数, 类,组件, 模块
-匈牙利命名法(属性+类型+描述)lpszTest以空字符串结尾的长整型指针 (C、C++)

概述:

我们可以结合 v-bind 指令和常见命名法来创建我们模板中的动态 class & 动态 style

  • 基本语法:v-bind:class(:style)、 v-bind:style (:class)
  • Vue 对于上述的命名法都会做适配
  • Vue 底层对v-bind:classv-bind:style进行了特殊的封装
  • 形式较多, 对象和数组的绑定方式
  • 具体参考手册 https://cn.vuejs.org/guide/essentials/class-and-style.html

1. :class

  • 字符串绑定
export default {
  data() {
    return {
      classStr: 'container active red'
    }
  }

  template: `
    <div :class="classStr"></div>
  `
};
  • 数组绑定
export default {
  data() {
    return {
      classArr: ['container', 'active', 'red'],
    }
  }

  template: `
    <div :class="classArr"></div>
  `
};
  • 对象绑定
export default {
  data() {
    return {
      classObject: {
        container: true,
        active: true,
        red: false
      },
    }
  }

  template: `
    <div :class="classObject"></div>
  `
};

补充

  1. 上树的用法是可以嵌套使用的
  2. 组件上也可以动态绑定class值
  3. 在 Vue3 中, 如果你的组件有多个根元素,你将需要指定哪个根元素来接收这个 class。你可以通过组件的 $attrs 属性来实现指定:

2. :style

  • 字符串绑定
export default {
	data() {
    return {
      styleStr: 'color: red;'
    };
  },
  
  template: `
    <div :style="styleStr">Hello world</div>
  `
};
  • 对象绑定
export default {
	data() {
    return {
      styleObj: {
        display: 'block',
        color: 'red'
      }
    };
  },
  
  template: `
    <div :style="styleObj">Hello world</div>
  `
};

补充点

  • 自动前缀添加:当你在 :style 中使用了需要浏览器特殊前缀的 CSS 属性时,Vue 会自动为他们加上相应的前缀
  • 自动匹配前缀:Vue 是在运行时检查该属性是否支持在当前浏览器中使用。如果浏览器不支持某个属性,那么将尝试加上各个浏览器特殊前缀,以找到哪一个是被支持的。
  • 数组绑定
export default {
  data() {
    return {
      style1: {},
      style2: {},
    }
  },

  template: `
    <div :style="[style1, style2]"></div>
  `
};
  • 样式多值

你可以对一个样式属性提供多个 (不同前缀的) 值,举例来说:

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

数组仅会渲染浏览器支持的最后一个值。在这个示例中,在支持不需要特别前缀的浏览器中都会渲染为 display: flex