zoukankan      html  css  js  c++  java
  • Vue#Class 与 Style 绑定

    绑定HTMLCLASS

    在我没看这之前,我觉得要写绑定class ,应该像绑定数据一样这么写

    class ={{class-a}}

    看官方教程时,不推荐这么写,推荐这样

    v-bind:class="{ 'class-a': isA, 'class-b': isB }"

    官方的解释,我觉得还是挺接地气的,最起码我能看的懂。

    数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是属性,我们可以用 v-bind 处理它们:我们只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在v-bind 用于 class 和 style 时,Vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。

    可以用对象语法来处理它们:

    可以这样:https://jsfiddle.net/miloer/36ek1uco/

    也可以这样:https://jsfiddle.net/miloer/36ek1uco/1/

    也可以使用数组语法来处理:

    https://jsfiddle.net/miloer/36ek1uco/2/

    我觉得在样式里用表达式判断,这么做挺有创意的,不过个人感觉这么做又繁琐了点,不过官方说:

    当有多个条件 class 时这样写有些繁琐。在 1.0.19+ 中,可以在数组语法中使用对象语法:

    <div v-bind:class="[classA, { classB: isB, classC: isC }]">

    这样是不是好多了。

    绑定内联样式:

    这个和绑定HTMLCLASS 方法差不多。

    https://jsfiddle.net/miloer/36ek1uco/3/

    https://jsfiddle.net/miloer/36ek1uco/4/

    自动添加前缀

    这个我觉得挺方便的,当使用v-bind:style 需要添加前缀CSS时,Vue.js 会自动侦测并添加相应的前缀。

     

    v-bind

    • 缩写: :
    • 类型: * (with argument) | Object (without argument)
    • 参数: attrOrProp (optional)
    • 修饰符:用法:动态地绑定一个或多个 attribute,或一个组件 prop 到表达式。
      • .sync - 双向绑定,只能用于 prop 绑定。
      • .once - 单次绑定,只能用于 prop 绑定。
      • .camel - 将绑定的特性名字转回驼峰命名。只能用于普通 HTML 特性的绑定,通常用于绑定用驼峰命名的 SVG 特性,比如 viewBox
    • 在绑定 class 或 style 时,支持其它类型的值,如数组或对象。

      在绑定 prop 时,prop 必须在子组件中声明。可以用修饰符指定不同的绑定类型。

      没有参数时,可以绑定到一个对象。注意此时 class 和 style 绑定不支持数组和对象。

    • 示例:
      <!-- 绑定 attribute -->
      <img v-bind:src="imageSrc">
      
      <!-- 缩写 -->
      <img :src="imageSrc">
      
      <!-- 绑定 class -->
      <div :class="{ red: isRed }"></div>
      <div :class="[classA, classB]"></div>
      <div :class="[classA, { classB: isB, classC: isC }]"></div>
      
      <!-- 绑定 style -->
      <div :style="{ fontSize: size + 'px' }"></div>
      <div :style="[styleObjectA, styleObjectB]"></div>
      
      <!-- 绑定到一个对象 -->
      <div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
      
      <!-- prop 绑定,"prop" 必须在 my-component 组件内声明 -->
      <my-component :prop="someThing"></my-component>
      
      <!-- 双向 prop 绑定 -->
      <my-component :prop.sync="someThing"></my-component>
      
      <!-- 单次 prop 绑定 -->
      <my-component :prop.once="someThing"></my-component>
    • 另见:
  • 相关阅读:
    Vijos训练计划 1304回文数
    18.03.03 位运算作业三则
    18.03.01 codevs1014 装箱问题
    Wikioi 1020 孪生蜘蛛 Label:Floyd最短路
    TYVJ P1004 滑雪 Label:记忆化搜索
    洛谷 P1118 数字三角形游戏 Label:dfs
    TYVJ P1015 公路乘车 &&洛谷 P1192 台阶问题 Label:dp
    洛谷 P1147 连续自然数和 Label:等差数列
    洛谷 P1019 单词接龙 Label:dfs
    洛谷 P1025 数的划分 Label:dp
  • 原文地址:https://www.cnblogs.com/moustache/p/5454135.html
Copyright © 2011-2022 走看看